Generics
Suppose you want a function that returns the last item of a list. With any, you lose all type information:
function last(items: any[]): any {
return items[items.length - 1];
}
const n = last([1, 2, 3]); // n is 'any': TypeScript can no longer help you
A generic function takes a type parameter, written in angle brackets, and uses it like a variable for types:
function last<T>(items: T[]): T | undefined {
return items[items.length - 1];
}
const n = last([1, 2, 3]); // n is number | undefined
const s = last(["a", "b"]); // s is string | undefined
TypeScript works out T from what you pass in. The function works for every type, and each call keeps its exact type.
Several type parameters and constraints
You can have more than one type parameter, and constrain one with extends to say what it must be:
function pluck<T, K extends keyof T>(item: T, key: K): T[K] {
return item[key];
}
pluck({ name: "Ana", age: 30 }, "age"); // number
pluck({ name: "Ana", age: 30 }, "email"); // error: not a key of the object
Record<K, V> is a built-in generic type for "an object whose keys are K and values are V".
Your task
first<T>(items: T[]): T | undefined: the first item, orundefinedfor an empty list.groupBy<T, K extends string>(items: T[], key: (item: T) => K): Record<K, T[]>: puts items into lists by the key the function returns.