Skip to content
Preptima
mediumConceptDesignMidSeniorStaff

How do you use TypeScript's type system to make invalid states unrepresentable in a service?

4 min readUpdated 2026-08-15

Answer

Short answer

You shrink the set of values the compiler accepts: discriminated unions instead of optional-field soup, branded types so one id cannot stand in for another, and a never-typed fallback that fails the build when a variant is added.

Was this answer helpful?

Likely follow-ups

  • Where exactly do you draw the validation boundary in a service that also reads from its own database?
  • How do branded types survive a JSON round trip through a queue, and what has to re-establish the brand?
  • When is a runtime tagged class hierarchy a better fit than a discriminated union of plain objects?
  • What breaks about exhaustiveness checking if the union is declared in a library you do not control?

Related questions

Further reading