§ GARDEN · TYPESCRIPT · CLASS OPEN
NODE FILE · ENTRY
Discriminated Unions for State Machines
FILED UNDER · TYPESCRIPT
①Read
②Meta
Model impossible states as unrepresentable using tagged unions and exhaustive switch statements.
The most common source of bugs isn't logic errors — it's impossible states that your types allow. A loading indicator that shows alongside an error message. A form with both 'pristine' and 'dirty' flags set to true. Discriminated unions make these states literally unrepresentable in your type system.
The Pattern
Define a union where each member has a literal type or status field (the discriminant). TypeScript narrows the type in each branch of a switch statement. Add a never check in the default case and the compiler will tell you if you forgot a state.
DTNRWORKSHOP ARMAMENTSSN 2012.OTT.0176