Generic Functions
Let TypeScript infer the type parameter from the arguments you pass.
Syntax
function first<T>(arr: T[]): T { return arr[0]; }When you call a generic function, TypeScript can usually infer the type argument from the values you pass, so you rarely write the <T> explicitly.
This makes utility functions like "return the first element of an array" both reusable and precise.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- A first() utility function is generic so it returns the correctly typed first element of any array.
- A swap function is generic so it swaps the elements of a typed two-element tuple without losing type information.
- A pick function is generic and constrained by keyof so it extracts a typed property from any object.
More examples
Generic function with inference
TypeScript infers T from the passed array, so the return type is automatically the element type of the array.
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
const n = first([1, 2, 3]); // number | undefined
const s = first(['a', 'b', 'c']); // string | undefinedGeneric pair swap
Uses two type parameters A and B to model a swap that preserves each position's type in the reversed tuple.
function swap<A, B>(pair: [A, B]): [B, A] {
return [pair[1], pair[0]];
}
const swapped = swap([1, 'hello']); // [string, number]Generic pick utility
A constrained generic that picks a subset of an object's keys, inferring the exact return type from the key list.
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
const result = {} as Pick<T, K>;
keys.forEach((k) => { result[k] = obj[k]; });
return result;
}
const user = { id: 1, name: 'Alice', email: '[email protected]' };
const slim = pick(user, ['id', 'name']); // { id: number; name: string }
Discussion