Generic Constraints: Narrowing Type Parameters
Use extends to enforce shape requirements on generics.
Welcome
Advanced generic constraints let you narrow what types can be used as type arguments, enabling type-safe operations on complex shapes.
Constraint Recap
T extends U restricts T to types that are subtypes of U. This gives TypeScript knowledge about T's shape inside the function.
function len<T extends { length: number }>(val: T): number {
return val.length;
}All lessons in this course
- keyof and Indexed Access Types
- Generic Constraints: Narrowing Type Parameters
- Conditional Types: T extends U ? X : Y
- Distributive Conditional Types