Generics
Type-safe generic functions and types
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
console.log(first([1, 2, 3])); // inferred T = number
console.log(first(["a", "b", "c"])); // inferred T = string
// Generic with constraint
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
console.log(longest("hello", "hi"));
console.log(longest([1, 2, 3], [4, 5]));
// Multiple parameters
function pair<A, B>(a: A, b: B): [A, B] {
return [a, b];
}
const p = pair("answer", 42); // [string, number]
console.log(p);
// Default type parameter
function wrap<T = string>(value: T): { value: T } {
return { value };
}
console.log(wrap("hi"));
console.log(wrap<number>(42));