Discriminated unions

Topic 4 of 5 in Unions and narrowing7 min readIntermediateFree course

Overview

Narrowing object unions with in works, but it’s fragile. TypeScript’s favourite pattern for “data that comes in several shapes” is the discriminated union (also called a tagged union): every member has a common property with a different literal value, and checking that one property tells TypeScript everything. It’s the single most useful modelling technique in TypeScript.

The pattern

TypeScript
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Rect = { kind: "rect"; width: number; height: number };

type Shape = Circle | Square | Rect;

Each member has a kind property whose type is a different literal. kind is the discriminant. Now:

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

Discriminated unions. Three shapes share a kind property: kind: “circle” with radius, kind: “square” with side, and kind: “rect” with w and h. type Shape = Circle | Square | Rect — the shared kind property tells them apart. In function area(s: Shape), switch (s.kind) narrows each case: case “circle” returns Math.PI * s.radius ** 2 with s: Circle; case “square” returns s.side ** 2 with s: Square; case “rect” returns s.w * s.h with s: Rect; and default: { const unreachable: never = s; return unreachable; }. Add a new shape and forget a case: the never line becomes a compile error, pointing at the missing case.

In each case, TypeScript narrows shape to exactly one member, so you can use radius, side or width safely — and only where they exist:

TypeScript
case "square":
  return shape.radius;
  // error TS2339: Property 'radius' does not exist on type 'Square'.

The discriminant can have any name (kind, type, status, tag) and any literal type (strings are most common; numbers and booleans also work). It just has to be present in every member.

Exhaustiveness checking

What if someone adds a triangle to Shape and forgets to update area? Add a default branch that assigns the value to never:

TypeScript
function assertNever(value: never): never {
  throw new Error(`Unhandled case: ${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 "rect":   return shape.width * shape.height;
    default:       return assertNever(shape);
  }
}

When every case is handled, shape in the default branch is never, so the call compiles. Add Triangle to the union, and the default branch receives a Triangle:

Text
error TS2345: Argument of type 'Triangle' is not assignable to parameter of type 'never'.

The compiler now lists every switch in the codebase that needs a new case. That’s the kind of safety that makes large refactors routine. (If the value somehow arrives at run time anyway — say, from bad JSON — assertNever throws a clear error.)

Making impossible states impossible

Compare two ways to model a data request:

TypeScript
// ✗ Loose: every combination is allowed
type Request = {
  loading: boolean;
  data?: string[];
  error?: string;
};

Nothing stops { loading: true, data: [...], error: "boom" } — loading, succeeded and failed at once. Every piece of code that reads it has to guess.

TypeScript
// ✓ Precise: exactly four valid states
type RequestState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; message: string };

Now data only exists on success and message only on error. You can’t read data without first checking the status — and you can’t construct an invalid combination. This idea — make impossible states unrepresentable — removes whole families of bugs.

Where discriminated unions shine

  • UI states: idle / loading / success / error, as above.
  • Actions and events: { type: "add"; item: Item } | { type: "remove"; id: string } | { type: "clear" } — the pattern behind React’s useReducer and Redux.
  • Results: { ok: true; value: T } | { ok: false; error: E } (Error handling).
  • Messages between services, web workers or WebSocket clients.
  • Parsed data: tokens in a parser, nodes in a syntax tree.

Narrowing without switch

Any check on the discriminant narrows:

TypeScript
if (state.status === "success") {
  console.log(state.data);       // ✓
}

const errors = results.filter((r) => r.status === "error");
// errors: { status: "error"; message: string }[] — TypeScript infers the narrowing filter

Narrowing also follows a destructured discriminant, or a check stored in a const, as long as everything involved is const:

TypeScript
const { status } = state;
if (status === "success") console.log(state.data);   // ✓ state narrowed

const failed = state.status === "error";
if (failed) console.log(state.message);              // ✓ narrowed through the alias

Recipe: give every variant a literal kind/type/status, switch on it, and end with default: return assertNever(x). The compiler will remember every case for you.

Exercise

Request states

Model a data request as a discriminated union RequestState with four members: { status: "idle" }, { status: "loading"; startedAt: number }, { status: "success"; data: string[] } and { status: "error"; message: string; retryable: boolean }. Write render(state: RequestState, now: number): string with a switch on status returning Nothing yet, Loading… (3s) (seconds since start), 3 results: a, b, c and Error: <message> (try again) (or without (try again) if not retryable). Add an exhaustiveness check with a never helper. Print the result for one state of each kind.

TypeScript
// RequestState

// assertNever()

// render()

const now = 10_000;

Summary

  • A discriminated union is a union of object types that share a literal property (the discriminant), such as kind or status.
  • Checking the discriminant (switch (shape.kind)) narrows to exactly one member, unlocking its properties.
  • An assertNever(value: never) call in the default branch makes TypeScript report any case you forgot to handle.
  • Discriminated unions make impossible states impossible: no data without success, no message without an error.
  • They model events, actions, API results, UI states and messages — anywhere data comes in several shapes.