Generics
Generics let you write one function or type that works with many types while keeping them checked. The type is a parameter, written in angle brackets: <T>.
Generics let you write code once that works for many types without losing type safety - like a box that can hold any item but remembers what kind of item it is. Arrays (Array<T>), promises (Promise<T>) and most libraries use them.
Example
Generic interfaces
Example
Constraints with extends
Sometimes T must have certain properties. T extends ... sets the minimum:
Example
A generic class
Example
Key points
- <T> is a type parameter.
- Generic functions, interfaces and classes keep types precise.
- extends adds constraints to T.
📝 Test yourself
1. Why use generics?
2. What does T extends { price: number } mean?
3. Fill in the generic type for a list of strings:
const res: ApiResponse<> = { ok: true, data: ["a"] };
