← TypeScript learning path
TypeScript · Module 7 of 10

Generics

Write reusable code that works with many types safely.

📖 Key ideas

  1. function first<T>(items: T[]): T { return items[0]; }
  2. T is a type parameter filled in when used.
  3. Generic interfaces: interface ApiResponse<T> { data: T }.
  4. Constraints: <T extends { id: number }>.
  5. 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