midTypeScript
What are Discriminated Unions and how do they improve type safety?
Updated May 4, 2026
Short answer
A pattern where multiple types share a common literal property used to narrow down the specific type in a union.
Deep explanation
Discriminated Unions (or Tagged Unions) consist of three ingredients: a set of types, a common 'discriminant' property with literal types, and type guards. When you check the discriminant property in a switch or if-statement, TypeScript automatically narrows the union to the specific member that matches that literal value, allowing safe access to its unique properties.
Real-world example
Handling different states of a network request (Loading, Success, Error) in a Redux reducer or React component.
Common mistakes
- Using a non-literal type (like a general string) as the discriminant, which prevents the compiler from narrowing correctly.
Follow-up questions
- What is exhaustive checking?