Discriminated union

A union of object types sharing a literal tag that enables safe narrowing.

Since TS 2.0 Spec ↗

Syntax

{ kind: "a"; ... } | { kind: "b"; ... }

Examples

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; size: number };

function area(s: Shape) {
  switch (s.kind) {
    case 'circle': return Math.PI * s.radius ** 2;
    case 'square': return s.size ** 2;
  }
}
type Result<T> =
  | { ok: true; value: T }
  | { ok: false; error: string };

Notes

Each member shares a common property (the discriminant) with a unique literal type. Switching or branching on that property narrows to the matching member. Add a `never` default case for compile-time exhaustiveness checking.

See also