Learning on Web Dev Open is free for all.

Systems Thinking > TypeScript as a design toolGenerics, only where they earn it
Phase 03TypeScript as a design tool162 of 434

Generics, only where they earn it

A generic is a promise that a relationship between two types holds. If there is no relationship, you have written an obstacle.

Concept15 minAI adversary

A type parameter is worth having when it connects an input to an output. first<T>(items: T[]): T | undefined is a real promise: whatever you put in, that is what you get back. A parameter used in exactly one position promises nothing: it is an alias for the argument type and could be unknown, or a plain union, with less noise.

Constraints are where generics get their teeth. <K extends keyof T> says the key must belong to the object, so a typo is a compile error rather than an undefined at runtime. <T extends { id: string }> lets a function work over anything identifiable without demanding it be your exact entity type. Both preserve information; neither requires the reader to hold a variance rule in their head.

The failure mode is a signature with four parameters, two conditional types and a mapped type, wrapping a function whose body is nine lines. The types are now harder to change than the code they describe, and nobody will refactor them. Write the concrete version, use it in three places, and only then extract the shape that all three actually share.

You should now be able to

  • Justify a type parameter by the relationship it preserves
  • Replace a pointless generic with a concrete type
Ask the community

Loading…