Dev.to
7/9/2026

TypeScript Discriminated Unions: Make Illegal States Unrepresentable
Short summary
Discriminated unions in TypeScript let you model state so that invalid combinations are compile errors rather than runtime crashes. By replacing bags of optional properties with tagged union variants, the compiler narrows types automatically and guarantees field presence per state. The assertNever pattern turns unhandled variants into compile-time checklists, making large refactors safe and exhaustive.
- •Optional-property interfaces permit nonsensical state combinations that cause runtime bugs
- •Discriminated unions use a literal discriminant field to enforce only valid states at compile time
- •assertNever in default switch branches forces the compiler to flag every unhandled variant during refactors
Generated with AI, which can make mistakes.
Is this a good recommendation for you?



