Advertisement
Advanced TypeScript, Discriminated Unions & Exhaustiveness Checking

How do you nest discriminated unions to model a state machine with multiple independent dimensions of state?

Short answer

Combine multiple discriminants (or nest one discriminated union inside a variant of another) when a single state genuinely has more than one independent axis of variation — though often it's cleaner to flatten everything into a single discriminant enumerating every valid…

Save TypeScript mock interview
Advertisement
AModel answer
Combine multiple discriminants (or nest one discriminated union inside a variant of another) when a single state genuinely has more than one independent axis of variation — though often it's cleaner to flatten everything into a single discriminant enumerating every valid COMBINATION of states, avoiding impossible in-between states entirely.
type FetchState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: string; cached: boolean }
  | { status: 'error'; error: string; retryable: boolean };
// 'cached' and 'retryable' only exist on their relevant variant, preventing impossible combinations
Real-world example
Modeling a network request state machine where 'cached' only makes sense once data has successfully loaded.
Likely follow-ups
  • What is the 'make impossible states impossible' design principle, and how do discriminated unions embody it?
Related topics