← TypeScript learning pathTypeScript · Module 7 of 10
Generics
Write reusable code that works with many types safely.
📖 Key ideas
- function first<T>(items: T[]): T { return items[0]; }
- T is a type parameter filled in when used.
- Generic interfaces: interface ApiResponse<T> { data: T }.
- Constraints: <T extends { id: number }>.
- Arrays and Promises are generic: Array<T>, Promise<T>.
💡 Real-life example: Generics are a lunch box that fits any food but remembers exactly what you packed.
GenericCode with a type parameter
<T>Type parameter placeholder
ConstraintLimit with extends
Promise<T>Generic promise of T