The pattern
A discriminated union is a union of object types that all share one literal tag field. Switching on that tag lets TypeScript narrow to a single variant and reveal its unique properties.
The three ingredients
- A common tag property, often named kind or type, on every variant.
- Each variant gives that tag a distinct literal value.
- Code branches on the tag using switch or if to select a variant.
Why narrowing works
When you compare the tag against a literal, the compiler eliminates variants whose tag cannot match. Inside that branch the value is the matching variant, so its specific fields become accessible without casts.
Exhaustiveness
Assigning the narrowed value to a never typed variable in the default branch forces a compile error if you add a new variant and forget to handle it. This turns a missing case into a build failure rather than a runtime surprise.
Where it shines
Model network responses as success and error variants, or shapes as circle and square. The tag keeps each variant honest and the checker guides every branch.
Key idea
A shared literal tag lets the compiler narrow a union to one variant and unlock its fields without unsafe casts.