ReviseAlgo Logo

Type System Deep Dive

Discriminated Unions (Tagged Unions)

Master Discriminated Unions in TypeScript, discriminant keys, pattern matching with switch statements, exhaustiveness checks, and state machine modeling.

Last Updated: July 29, 2026 10 min read

A Discriminated Union (also called a Tagged Union or Algebraic Data Type) is one of TypeScript's most powerful architectural patterns for modeling complex, mutually exclusive states.

A discriminated union consists of object types that share a common literal property (the Discriminant / Tag).

1. Structure of a Discriminated Union

A discriminated union requires three components:

1. Object types with a common property name (e.g. type or kind or status). 2. That common property holds literal types ("success", "error", "loading"). 3. A union of those object types.

2. Type Narrowing via switch Statements

TypeScript automatically narrows the union variant based on inspecting the discriminant tag:

3. Enforcing Exhaustiveness Checking (never Type)

You can ensure every union variant is handled by adding a default case typed as never. If a developer adds a new state variant to ApiState without updating the switch statement, TypeScript flags a compile-time error.

4. Interactive Code Playground

Test discriminated unions below:

5. Summary Checklist

  • [x] Give every variant object a shared property with unique string/number literal values.
  • [x] Use switch(obj.discriminant) for clean control flow analysis narrowing.
  • [x] Use never in default branches to guarantee compile-time exhaustiveness checking.