Handbooks / TypeScript / Chapter 4
Generics
7 pages · ~5 min✓ Reviewed
Builds on Narrowing. Next up: Utility and Mapped Types.
Generics Mental Model
1. What a Generic Is
- A generic is a type-level parameter:
function id<T>(x: T): T - One declaration works for many types without losing type info
| any | T | |
|---|---|---|
| Input type | discarded | linked to output |
id(5) returns | any | literal 5 |
2. Inference and Erasure
- Inferred from call arguments:
id('a')gives T ='a' - Pass explicitly when inference fails:
id<string>('a')
typescript
function id<T>(x: T): T { return x } id(5) // T = 5 id('a') // T = 'a' id<string>('a') // T = string
explicit argument overrides inference
Erased at runtime
T exists only for the compiler. So no new T() and no typeof T.
3. Interview Point
- What do generics fix over
any? T links input to output, so type info survives - Available at runtime? No, erased;
new T()is impossible
Generic Functions, Interfaces and Classes
1. Declaring Generics
| Form | Declare | Use |
|---|---|---|
| Function | function first<T>(a: T[]): T | undefined { return a[0]; } | first([1, 2]) |
| Interface | interface Box<T> { value: T } | Box<number> |
| Call signature | interface Fn<T> { (x: T): T } | Fn<string> |
Constraints with extends
1. Constraint syntax
T extends { length: number }: callers may pass only types that have length- Bare
Tis unknown-like, sox.lengtherrors Tkeeps the specific type:len([1, 2])givesT = number[],len('abc')givesT = string
typescript
function len<T extends { length: number }>(x: T) { return x.length }
accepts string, array, any object with length
2. Dependent params and constructors
K extends keyof Tties the key to the object
Defaults, keyof and Indexed Access
1. Default type parameters
interface Res<T = unknown> { data: T }, soResmeansRes<unknown>- Applied only when T is not given and not inferred
- Defaulted params go after required ones
- Default must satisfy the constraint:
<T extends object = {}>
2. keyof and indexed access
| Type | Gives |
|---|---|
Common Generic Mistakes
1. Smells in the signature
function f<T>(x: T): void: T used once relates nothing, so it is a smell- Each T should link two positions, such as param and return
as Tor{} as Thides errors; the compiler cannot verify it
2. Constraint traps
| Mistake | Why it fails | Fix |
|---|---|---|
T extends string, return 'a' |
Generics Cheat Sheet
1. Declare
| Form | Syntax |
|---|---|
| Function | function f<T>(x: T): T |
| Interface | interface I<T> { v: T } |
| Class | class C<T> {} |
| Alias | type A<T> = T[] |
2. Constrain and index
Check yourself
function len<T>(x: T) { return x.length } fails to compile. Why, and what is the fix?
- A bare
Tcould be anything, so the compiler knows no properties on it - Constrain it:
<T extends { length: number }>
Given get<T, K extends keyof T>(o: T, k: K): T[K], what is the type of get({a: 1, b: 'x'}, 'b')? What about get({a: 1}, 'c')?
string, becauseKis inferred as'b'andT['b']isstring- The second call is a compile error:
'c'is not inkeyof T