Discriminated unions
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
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:
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
}
}In each case, TypeScript narrows shape to exactly one member, so you can use radius, side or width safely — and only where they exist:
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:
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:
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:
// ✗ 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.
// ✓ 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’suseReducerand 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:
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 filterNarrowing also follows a destructured discriminant, or a check stored in a const, as long as everything involved is const:
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 aliasRecipe: give every variant a literal
kind/type/status,switchon it, and end withdefault: return assertNever(x). The compiler will remember every case for you.
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.
// RequestState
// assertNever()
// render()
const now = 10_000;type RequestState =
| { status: "idle" }
| { status: "loading"; startedAt: number }
| { status: "success"; data: string[] }
| { status: "error"; message: string; retryable: boolean };
function assertNever(value: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}
function render(state: RequestState, now: number): string {
switch (state.status) {
case "idle":
return "Nothing yet";
case "loading":
return `Loading… (${Math.round((now - state.startedAt) / 1000)}s)`;
case "success":
return `${state.data.length} results: ${state.data.join(", ")}`;
case "error":
return `Error: ${state.message}${state.retryable ? " (try again)" : ""}`;
default:
return assertNever(state);
}
}
const now = 10_000;
const states: RequestState[] = [
{ status: "idle" },
{ status: "loading", startedAt: 7_000 },
{ status: "success", data: ["a", "b", "c"] },
{ status: "error", message: "Network down", retryable: true },
];
for (const state of states) console.log(render(state, now));Summary
- A discriminated union is a union of object types that share a literal property (the discriminant), such as
kindorstatus. - Checking the discriminant (
switch (shape.kind)) narrows to exactly one member, unlocking its properties. - An
assertNever(value: never)call in thedefaultbranch makes TypeScript report any case you forgot to handle. - Discriminated unions make impossible states impossible: no
datawithout success, nomessagewithout an error. - They model events, actions, API results, UI states and messages — anywhere data comes in several shapes.