Everyday types · Lesson 6 of 12 · 19 min
Generics without the fear
A generic is a type parameter: a placeholder you fill in when you use the function. You've used them already: Array<string>, Promise<User>.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([1, 2, 3]); // number | undefined
const s = first(["a", "b"]); // string | undefinedTypeScript infers T from the argument. You rarely write first<number>(…) yourself.
Constraints
Use extends to say what a type parameter must have:
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
pluck(users, "email"); // string[]
pluck(users, "emial"); // ❌ typo caughtA rule of thumb
If a type parameter appears only once in the signature, you probably don't need it. Generics are for connecting an input to an output.
The exercises for this lesson are in the resources below. Do them in order; the last one types a useLocalStorage hook.