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
- How do you make the compiler fail when somebody adds a new variant to a union you switch on?mediumAlso on discriminated-unions and exhaustiveness5 min
- How do you use TypeScript to make a component's props hard to misuse?mediumAlso on discriminated-unions4 min
- You pass an object with extra properties to something typed to accept fewer. When does TypeScript complain, and when does it not?mediumAlso on type-safety5 min
- Your endpoint takes a typed request body and it still crashed on a missing field. How is that possible when it compiled?mediumAlso on zod4 min