Chapter 4: Generics - Linking Types Together
Runnable examples: examples/ch04-generics.ts
A generic type parameter is a variable at the type level. Its job is to link types: an input to an output, one argument to another, a key to a value.
The basic link
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
first(["a", "b"]); // string | undefined
Without T, you would have to choose between unknown (safe but useless to callers) and any (useful but unsafe). The type parameter keeps the information the caller already has.
Rule of thumb: a type parameter should appear at least twice in a signature. If it appears once, like function log<T>(value: T): void, it links nothing and unknown would do the same job.
Constraints
T extends X means “T can be anything, as long as it is a subtype of X”:
function longest<T extends { length: number }>(a: T, b: T): T { ... }
longest("apple", "fig"); // T = string
longest([1, 2, 3], [4]); // T = number[]
longest(10, 20); // Error: number has no length
Note the return type is T, not { length: number }: callers get back the exact type they passed in.
keyof constraints for safe property access
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
pluck(users, "name"); // string[]
pluck(users, "email"); // Error: not a key
T[K] is an indexed access type: the type of property K in T. Together with keyof, it lets functions be precise about the properties they touch.
How TypeScript chooses T
When you call a generic function, TypeScript collects inference candidates for each type parameter from the arguments and picks one. Things to know:
- Candidates from different arguments are not automatically unioned.
pair(1, "x")forpair<T>(a: T, b: T)infersT = numberfrom the first argument and then rejects"x". Pass the type explicitly (pair<number | string>(1, "x")) if you want a union. - Literal types are kept when the type parameter is constrained to a primitive (
T extends string), and widened otherwise. - Inference works left to right across arguments, so put the argument that should “decide” the type first.
const type parameters (TypeScript 5.0+)
Adding const asks TypeScript to infer as if the argument were written with as const:
function routes<const T extends readonly string[]>(paths: T): T { return paths; }
routes(["/home", "/about"]); // readonly ["/home", "/about"]
NoInfer (TypeScript 5.4+)
Sometimes a parameter should be checked against T but must not contribute to inferring it:
function createState<S extends string>(states: S[], initial: NoInfer<S>) { ... }
createState(["red", "yellow", "green"], "red"); // OK
createState(["red", "yellow", "green"], "blue"); // Error
Without NoInfer, "blue" would be another candidate and S would happily widen to include it.
Defaults
type ApiResponse<Data = unknown, Err = { message: string }> =
| { ok: true; data: Data }
| { ok: false; error: Err };
Defaults make generic types pleasant to use when most callers do not care about every parameter.
Generic classes
The examples include a small TypedEventEmitter<Events> where the event map links each event name to its payload type:
type AppEvents = { login: { userId: number }; logout: undefined };
const bus = new TypedEventEmitter<AppEvents>();
bus.on("login", (p) => p.userId); // p is { userId: number }
bus.emit("login", { id: 1 }); // Error: wrong payload shape
The trick is the method-level parameter E extends keyof Events, which ties the name argument to the payload type for each call.
Common generic mistakes
| Mistake | Better |
|---|---|
function f<T>(x: T): void (T used once) |
function f(x: unknown): void |
function get<T>(url: string): Promise<T> (caller chooses T, nothing checks it) |
Return unknown and validate, or accept a schema/parser argument that produces T |
Over-constraining: T extends string[] when you only read length |
T extends { length: number } or readonly unknown[] |
Returning the constraint instead of T |
Return T so callers keep their precise type |
The second row deserves emphasis: a generic return type that is not connected to any argument is a disguised type assertion. It looks safe and is not.
Check yourself
- Why does
pair(1, "x")fail, and what are two ways to make it work? - What does
NoInfer<S>change about type inference? - Why is
function parse<T>(json: string): Tmisleading?