Generics: T extends and constraints
Write generic functions and interfaces, constrain type parameters with extends, and use generic defaults for flexible APIs.
What Are Generics?
Generics allow you to write functions, classes, and interfaces that work with multiple types while keeping type safety. Instead of writing separate functions for each type, you write one generic function parameterised by a type variable.
A Simple Generic Function
The type parameter T is declared in angle brackets. TypeScript infers T from the argument type — no explicit annotation needed at the call site.
function identity<T>(value: T): T {
return value;
}
identity(42); // T is inferred as number, returns number
identity('hello'); // T inferred as string
identity<boolean>(true); // explicitAll lessons in this course
- Generics: T extends and constraints
- Utility Types: Partial Required Pick Omit
- Mapped Types and Conditional Types
- Narrowing: typeof instanceof discriminated unions