Lesson 8 of 9 · 25m
Make Illegal States Unrepresentable
Discriminated unions, exhaustive checks, mutually exclusive fields, and state machines encoded so invalid transitions become compile errors.
The strongest type design does not merely describe valid data — it refuses to describe invalid data. Every boolean flag matrix, nullable pair, and string status field is a chance to encode impossible combinations that later become production incidents. Advanced TypeScript is most valuable when it deletes those combinations from the language of the system.
Replace flag soup with states
// weak: 16 combinations, most meaningless
type LoadStateBad = { loading: boolean; error?: Error; data?: Report; empty: boolean };
// strong: exactly the states the UI understands
type LoadState =
| { status: "loading" }
| { status: "error"; error: Error }
| { status: "empty" }
| { status: "success"; data: Report };With the union version, data cannot exist while loading, an error cannot accompany success, and the UI cannot forget which shape it is handling. The compiler knows because status discriminates the union.
Exhaustiveness is a safety device
function renderState(state: LoadState) {
switch (state.status) {
case "loading": return spinner();
case "error": return errorPanel(state.error);
case "empty": return emptyPanel();
case "success": return reportView(state.data);
default: {
const exhaustive: never = state;
throw new Error(`Unhandled state: ${exhaustive}`);
}
}
}Add a fifth state and the build fails at never. That failure is a feature: it forces every decision point to acknowledge the new world.
Use types to encode phase-specific fields
type Checkout =
| { step: "cart"; items: CartItem[] }
| { step: "payment"; items: CartItem[]; paymentMethodId: string }
| { step: "confirmation"; orderId: string };A confirmation screen cannot accidentally render without an order id, and the cart step cannot pretend it already has payment data. This is how types prevent bugs instead of decorating them.
Field notes
- Optional properties often mean "this object is really two states." Split them before they multiply.
neverchecks only work if every return path is covered; avoid fall-through returns that bypass the default.- Runtime input still needs validation, but once parsed, keep the narrowed union intact as long as possible.
- Resist widening state to a generic interface because one consumer is lazy. Precision is the asset.
Was this lesson helpful?