Skip to main content

Generics

Generics create reusable components that work with multiple types.

Generic Functions

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

const n = first([1, 2, 3]); // number | undefined
const s = first(['a', 'b']); // string | undefined

Generic Constraints

function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}