Model safe TypeScript APIs with generics and narrowing
8 steps · about 4 h 20 min · Intermediate
- Separate values from their static types (guide, TypeScript documentation, 30 min)
Review the inference and annotation rules on which the public API will rely.
- Describe callable contracts (guide, TypeScript documentation, 35 min)
Model parameters, callbacks and overloads without exposing an unnecessarily broad signature.
- Preserve relationships with generics (guide, TypeScript documentation, 40 min)
Carry a caller's type through reusable logic instead of losing information to any or unknown.
- Constrain property names with keyof (reference, TypeScript documentation, 25 min)
Accept only keys that exist on the generic object being handled.
- Narrow discriminated unions (guide, TypeScript documentation, 40 min)
Make state variants explicit and force each branch to handle the right fields.
- Derive related object types (reference, TypeScript documentation, 30 min)
Transform an existing contract without maintaining a second drifting copy.
- Use standard utility types (reference, TypeScript documentation, 25 min)
Express common selections and transformations with familiar built-in vocabulary.
- Review the published type surface (guide, TypeScript documentation, 35 min)
Keep declarations precise and ergonomic while documenting where runtime checks remain necessary.