TExcelTAD
Home › TypeScript › TS Discriminated Unions

TypeScript Discriminated Unions

A discriminated union (also called a tagged union) is a union of object types that all share one property — the discriminant — whose value is a different literal in each member. Checking that one property tells TypeScript exactly which member you are holding, so it can narrow the whole object.

This pattern is one of the most useful tools in everyday TypeScript. It models things like API responses (loading / success / error), UI events, shapes, payment methods or the actions of a state machine — any value that can be "one of several kinds", where each kind carries different data.

Building a discriminated union

Each member has a kind property with a unique string literal type. The rest of the properties can differ freely:

ts · try it yourself
type Circle = { kind: "circle"; radius: number };
type Rect = { kind: "rect"; width: number; height: number };
type Triangle = { kind: "triangle"; base: number; height: number };

type Shape = Circle | Rect | Triangle;

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;     // shape: Circle
    case "rect":
      return shape.width * shape.height;      // shape: Rect
    case "triangle":
      return (shape.base * shape.height) / 2; // shape: Triangle
  }
}

const shapes: Shape[] = [
  { kind: "circle", radius: 1 },
  { kind: "rect", width: 3, height: 4 },
  { kind: "triangle", base: 6, height: 2 },
];

for (const s of shapes) {
  console.log(s.kind.padEnd(8), area(s).toFixed(2));
}
circle   3.14
rect     12.00
triangle 6.00

Notice that inside case "circle" you can use shape.radius, but shape.width would be an error — TypeScript knows that only a Circle has kind: "circle".

What a discriminant needs

Requirement Why
A property present in every member so you can always read it
A literal type in each member ("circle", 1, true) so each value identifies exactly one member
Unique values across members two members with the same tag can't be told apart

Common names for the discriminant are kind, type, tag and status. Literal types of numbers or booleans work too (ok: true / ok: false).

Exhaustiveness checking with never

What happens when you add a new member later? If a switch forgets to handle it, you want a compile error, not a silent bug. The trick is a default branch that assigns the value to a variable of type never — something that can only succeed if every case has already been handled.

Here a Hexagon has been added to the union, but area was not updated:

ts · try it yourself
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Hexagon = { kind: "hexagon"; side: number };
type Shape = Circle | Square | Hexagon;

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    default: {
      const unreachable: never = shape;
      throw new Error(`Unknown shape: ${JSON.stringify(unreachable)}`);
    }
  }
}

console.log(area({ kind: "square", side: 2 }));
main.ts(13,13): error TS2322: Type 'Hexagon' is not assignable to type 'never'.

The error points straight at the forgotten case. Adding it makes the default branch truly unreachable, and the code compiles:

ts · try it yourself
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Hexagon = { kind: "hexagon"; side: number };
type Shape = Circle | Square | Hexagon;

function assertNever(value: never): never {
  throw new Error(`Unhandled value: ${JSON.stringify(value)}`);
}

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    case "hexagon":
      return ((3 * Math.sqrt(3)) / 2) * shape.side ** 2;
    default:
      return assertNever(shape);
  }
}

console.log(area({ kind: "square", side: 2 }));
console.log(area({ kind: "hexagon", side: 2 }).toFixed(3));
4
10.392

Tip: A reusable assertNever helper like the one above is a common convention. It documents intent and gives a clear runtime error if bad data ever slips in from outside.

Modelling state

Discriminated unions shine when describing state. Instead of one object with many optional fields (data?, error?, loading?) that can combine into impossible states, each state carries exactly what it needs:

ts · try it yourself
type RequestState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; message: string };

function render(state: RequestState<string[]>): string {
  switch (state.status) {
    case "idle":
      return "Press the button to load.";
    case "loading":
      return "Loading...";
    case "success":
      return `Loaded ${state.data.length} items: ${state.data.join(", ")}`;
    case "error":
      return `Failed: ${state.message}`;
  }
}

const states: RequestState<string[]>[] = [
  { status: "idle" },
  { status: "loading" },
  { status: "success", data: ["tea", "coffee"] },
  { status: "error", message: "timeout" },
];
states.forEach((s) => console.log(render(s)));
Press the button to load.
Loading...
Loaded 2 items: tea, coffee
Failed: timeout

It is now impossible to have data and message at the same time, or to read data while still loading — the type checker won't allow it.

Destructuring caveat

Narrowing works on the object you checked. If you copy the tag into a separate variable with const { status } = state, TypeScript still narrows state when you check status (since TS 4.6, for const destructuring). But if you use let or reassign the object, the link is lost. Keeping the checks on state.status directly is the most reliable style.

Test yourself

What makes a union "discriminated"?

  1. Every member is a class
  2. Every member shares a property with a different literal type
  3. It contains never
  4. It is declared with enum

Why assign the value to a never variable in the default branch?

  1. To speed up the switch
  2. To convert the value to a string
  3. To get a compile error when a case is not handled
  4. It is required syntax for switch

Which is the best discriminant for { type: "a"; x: number } | { type: "b"; y: string }?

  1. x
  2. y
  3. type
  4. none, they need a class