Generics
Generics let you write code that works with many types while keeping full type safety. They're like function parameters, but for types. Arrays (Array<T>), Promises (Promise<T>), React's useState<T> and nearly every library use them.
The problem
A generic function
<T> declares a type parameter. TypeScript fills it in from the arguments:
The type flows in through the argument and out through the return type.
Multiple type parameters
Constraints: extends
Sometimes the generic type must have certain features. Use extends to require them:
keyof: safe property access
keyof T is the union of T's property names, and T[K] is the type of that property. Together they give you fully type-safe dynamic access.
Generic types and interfaces
One ApiResponse definition works for every endpoint.
Generic classes
Default type parameters
Practice
- Write
last<T>(items: T[]): T | undefined. - Write
groupBy<T, K extends string>(items: T[], getKey: (item: T) => K): Record<K, T[]>. - Use it to group these orders by status, and check that the result is fully typed.
✎ Check your understanding
1.What does <T> in function wrap<T>(value: T) mean?
2.What does K extends keyof T guarantee?