Generic Constraints with extends
Restrict type parameters to specific shapes.
Welcome
Generic constraints narrow what types can be passed as type arguments. Use `extends` to require that T has certain properties or matches a certain shape.
The Problem Without Constraints
Without constraints, TypeScript doesn't know what operations are valid on T, so it only allows operations common to all types.
function getLength<T>(val: T): number {
// return val.length; // Error — T might not have .length
}All lessons in this course
- Generic Functions: Type Parameters
- Generic Interfaces and Type Aliases
- Generic Constraints with extends
- Default Type Parameters