Model safe TypeScript APIs with generics and narrowing

8 steps · about 4 h 20 min · Intermediate

  1. Separate values from their static types (guide, TypeScript documentation, 30 min)

    Review the inference and annotation rules on which the public API will rely.

  2. Describe callable contracts (guide, TypeScript documentation, 35 min)

    Model parameters, callbacks and overloads without exposing an unnecessarily broad signature.

  3. 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.

  4. Constrain property names with keyof (reference, TypeScript documentation, 25 min)

    Accept only keys that exist on the generic object being handled.

  5. Narrow discriminated unions (guide, TypeScript documentation, 40 min)

    Make state variants explicit and force each branch to handle the right fields.

  6. Derive related object types (reference, TypeScript documentation, 30 min)

    Transform an existing contract without maintaining a second drifting copy.

  7. Use standard utility types (reference, TypeScript documentation, 25 min)

    Express common selections and transformations with familiar built-in vocabulary.

  8. Review the published type surface (guide, TypeScript documentation, 35 min)

    Keep declarations precise and ergonomic while documenting where runtime checks remain necessary.