Generics
A generic is a type parameter: a placeholder filled in by the caller or inferred from the arguments,
so one implementation serves many types without losing information. Generics are the difference
between function first(xs: any[]): any and a function whose return type is derived from its input.
The 60-second answer
Section titled “The 60-second answer”“Generics parameterise types the way functions parameterise values. You declare a type parameter on a
function, class, interface or alias, optionally constrain it with extends, and TypeScript infers it
from the call site. The important property is that information flows: identity<T>(x: T): T preserves
the input type, and pick<T, K extends keyof T> ties the key set to the object. On top of that,
mapped types transform every property of a type, and conditional types choose between two types based
on an assignability check — which is how the utility types are built.”
Generic functions
Section titled “Generic functions”function identity<T>(value: T): T { return value; }
function first<T>(items: readonly T[]): T | undefined { return items[0];}
const a = first([1, 2, 3]); // number | undefinedconst b = first(['x', 'y']); // string | undefinedInference reads the argument. When it cannot decide, the parameter falls back to unknown or to its
default. If you have to specify the type at every call site, the generic is not earning its keep.
Note readonly T[]: it accepts mutable and readonly arrays. Accepting T[] would reject a readonly
input for no reason.
Constraints
Section titled “Constraints”extends on a type parameter sets the minimum shape.
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] { return items.map((item) => item[key]);}
const users = [{ id: '1', name: 'Ada' }, { id: '2', name: 'Alan' }];pluck(users, 'name'); // string[]// pluck(users, 'age'); // error: 'age' is not a key of TT[K] is an indexed access type: the type of property K on T. With keyof T it is the
backbone of type-safe property access.
Generic interfaces and classes
Section titled “Generic interfaces and classes”interface Repository<T, Id = string> { findById(id: Id): Promise<T | null>; save(entity: T): Promise<T>;}
class InMemoryRepository<T extends { id: string }> implements Repository<T> { #items = new Map<string, T>(); async findById(id: string) { return this.#items.get(id) ?? null; } async save(entity: T) { this.#items.set(entity.id, entity); return entity; }}A default type parameter (Id = string) keeps the common case short. The constraint
T extends { id: string } documents why the body may use entity.id — the constraint is the
contract the implementation relies on.
keyof and indexed access
Section titled “keyof and indexed access”type User = { id: string; name: string; age: number };
type Keys = keyof User; // 'id' | 'name' | 'age'type NameType = User['name']; // stringtype Values = User[keyof User]; // string | numberThis is how libraries type get(obj, 'a.b.c') and setState({ name: 'x' }).
Mapped types
Section titled “Mapped types”A mapped type iterates over the keys of another type.
type MyPartial<T> = { [K in keyof T]?: T[K] };type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
// Key remapping with `as`:type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };type UserGetters = Getters<{ name: string; age: number }>;// { getName: () => string; getAge: () => number }Modifiers can be added or removed: { [K in keyof T]-?: T[K] } strips optionality, which is how
Required is defined.
Conditional types
Section titled “Conditional types”type IsString<T> = T extends string ? true : false;type ElementType<T> = T extends readonly (infer U)[] ? U : never;type Flatten<T> = T extends (infer U)[] ? Flatten<U> : T;type N = Flatten<number[][][]>; // numberinfer introduces a type variable inside the extends clause and captures whatever matched. This is
how ReturnType, Parameters and Awaited work.
Conditional types distribute over naked type parameters: with a union T, the check applies per
member. Wrap in a tuple to opt out:
type ToArray<T> = T extends unknown ? T[] : never;type A = ToArray<string | number>; // string[] | number[] (distributed)
type ToArray2<T> = [T] extends [unknown] ? T[] : never;type B = ToArray2<string | number>; // (string | number)[] (not distributed)Patterns worth memorising
Section titled “Patterns worth memorising”// Typed event maptype Handler<E> = { [K in keyof E]: (payload: E[K]) => void };
// Result instead of throwingtype Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };
// Branded primitives to stop mixing idstype UserId = string & { readonly __brand: 'UserId' };
// Exhaustivenessfunction assertNever(x: never): never { throw new Error(`Unexpected: ${JSON.stringify(x)}`); }Branded types answer “how do I stop passing an OrderId where a UserId is expected” when both are
strings. The brand is erased at runtime, so it is compile-time discipline only.
Follow-up questions
Section titled “Follow-up questions”- When is a generic worse than a union type?
- Why does a conditional type distribute, and how do you stop it?
- What is the difference between
T extends Uin a constraint and in a conditional type? - How do you constrain a key parameter to only string-valued properties?
Common traps
Section titled “Common traps”- Generic parameters that appear once. Ceremony with no safety.
- Using
anyinside a generic body. You defeat the parameter you declared. - Forgetting
readonlyon array parameters. It needlessly rejects readonly inputs. - Deeply nested conditional types. Unreadable, with terrible error messages; prefer a union or an overload.
- Assuming inference works from the return type. It works from arguments and contextual positions.