← Lessons

quiz vs the machine

Gold1420

Frontend

Discriminated Unions

Tag each variant so the compiler can narrow a union safely.

5 min read · core · beat Gold to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. What makes a union discriminated?

2. How does assigning to a never variable in the default branch help?