Generic Functions and Types
- Type parameters. A generic function links types: first<T>(items: T[]): T promises to return the same kind it received.
- Generic interfaces. Containers are generic types: Result<T> or Paged<T> wrap any payload while keeping its identity.
- Inference does the work. Callers rarely write the type argument: the compiler infers T from the arguments you pass.
Constraints and Relationships
- extends constraints. A constraint bounds what T may be: <T extends {id: string}> allows only values carrying an id.
- keyof relationships. The pattern <T, K extends keyof T> ties a key to its object, so get(user, "name") is checked against real keys.
- Defaults for type parameters. Type parameters may carry defaults: Response<T = unknown> stays usable without an argument.
Designing Reusable Typed APIs
- Generalise from duplication. Write the concrete version twice, THEN extract the generic: premature abstraction guesses wrong.
- Return-type honesty. A good generic API returns precise types: map over User[] must yield exactly what the callback produced.
- Keep signatures readable. If a signature needs a paragraph to read, split it: cleverness in types is a cost every caller pays.
Before and after this level
- Before: Level 4: Functions: Function Types and Signatures, Optional, Default and Rest Parameters, Overloads and Callback Types.
- Next: Level 6: Advanced Type Transformations: keyof, typeof and Indexed Access, Mapped and Conditional Types, Template Literal Types.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does TypeScript Level 5: Generics cover?
Generic Functions and Types, Constraints and Relationships, Designing Reusable Typed APIs: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 4: Functions, which covers Function Types and Signatures, Optional, Default and Rest Parameters, Overloads and Callback Types.