Skip to content

Discriminated Union

In one line

A discriminated union is a union of object types that share a common property (the discriminant), enabling type narrowing via switch statements.

In simple words

A discriminated union is a pattern where multiple object types share a common property with different literal values. This property (the discriminant) lets TypeScript narrow the type in switch statements.

For example, type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number }. The kind property is the discriminant. In switch (shape.kind), TypeScript narrows shape to the correct type in each case.

Discriminated unions are the idiomatic way to model variant data in TypeScript — different shapes of data with a common tag. They are used for state machines, AST nodes, API responses, and Redux actions.

Example

typescript
type Result =
  | { ok: true; value: number }
  | { ok: false; error: string };

function handle(r: Result) {
  switch (r.ok) {
    case true: return r.value;  // narrowed to success
    case false: return r.error; // narrowed to failure
  }
}

The 'ok' property is the discriminant. switch narrows the type in each case.

Related terms

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary