Skip to content
TypeScript

Generic Functions

Define and use generic functions.

By EZ4Code Team
genericfunction

Code

function identity<T>(value: T): T {
  return value;
}

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

// Multiple type parameters
function pair<K, V>(key: K, value: V): [K, V] {
  return [key, value];
}

// Generic constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

Explanation

Generics make functions reusable across multiple types; constraints can limit the type scope.

More TypeScript Snippets