Discriminated Unions: The Labelled Boxes

Discriminated Unions: The Labelled Boxes in TypeScript: A pathology lab receives blood samples all day, and every tube arrives with a coloured cap: a lavender…

The Analogy: The Coloured-Cap Tubes at a Pathology Lab

A pathology lab receives blood samples all day, and every tube arrives with a coloured cap: a lavender cap, a grey cap, a light-blue cap, and so on. The colour is not decoration. It is a strict code that tells the technician exactly what additive is inside the tube and therefore how the sample must be handled, which analyser it goes to, and what it can be tested for. A lavender-cap tube holds an anticoagulant for blood counts; a grey-cap tube holds a preservative for glucose; a light-blue tube holds citrate for clotting studies. The technician reads the cap and knows the whole story without prising the tube open, because the cap and the contents are guaranteed to match. A discriminated union is that rack of colour-coded tubes: a set of object shapes that share one common field, the cap colour, whose value is a fixed literal, and the compiler reads that field to know precisely which shape it is holding and which other fields come with it.

The alternative the lab is trying to avoid is a rack of identical clear tubes each carrying a set of optional stickers: a "has anticoagulant?" sticker, a "has preservative?" sticker, a "has citrate?" sticker. With three independent optional stickers there are eight sticker combinations, and almost all of them are nonsense: a tube cannot sensibly hold both the anticoagulant and the citrate, yet nothing about the stickers forbids it. In code that is the shape { anticoagulant?: boolean; preservative?: boolean; citrate?: boolean }, a bag of optional fields whose combinations are mostly meaningless and every one of which must be checked before use. The coloured cap replaces all of that with a single field that has exactly one valid value per genuine tube type, so the impossible combinations simply cannot be assembled.

What the cap buys the technician is that each tube type carries precisely the extra information it needs and no more. A lavender-cap tube records a cell-count field; a light-blue tube records a clotting-time field. You would never look for a clotting time on a lavender tube, and the lab's system will not even let you record one there, because that field belongs only to the light-blue shape. In a discriminated union the payload fields live on the member that owns them: the "success" member carries the data, the "error" member carries the message, and the compiler makes the data field reachable only after it has confirmed, by reading the discriminant, that you are in the member that has it. The label does the narrowing, and the narrowing unlocks exactly the right fields.

The failure mode the lab guards against hardest is a cap whose colour is not one of the fixed codes, or a bench process that quietly ignores a colour it was not updated to recognise. If a tube turned up with a cap in some arbitrary shade rather than one of the defined colours, the whole coding scheme collapses, because the technician can no longer read handling from colour; that is the discriminated-union rule that the shared field must be a literal in every member, since a field typed as an open string carries no code the compiler can read. Worse in daily practice is the bench that handles the three colours it knows and silently sets aside any tube whose colour it does not, so when a new cap colour is introduced those samples are dropped without anyone noticing. The defence is a final catch-all step that refuses to pass an unrecognised colour, which in code is an exhaustiveness check that turns a newly added union member into a compile error at every switch that forgot to handle it, rather than a sample silently lost at runtime.


Syntax or Core Structure

A discriminated union is several object types joined with a shared field whose value is a distinct literal in each. The compiler narrows on that field, so a switch over it makes each member's own payload fields available only in its branch.

// src/state.ts
interface Report {
    name: string;
}

type State =
    | { status: "idle" }
    | { status: "loading" }
    | { status: "success"; report: Report }
    | { status: "error"; message: string };

function render(state: State): string {
    switch (state.status) {
        case "idle":
            return "ready";
        case "loading":
            return "loading";
        case "success":
            return "ok:" + state.report.name;   // report exists only here
        case "error":
            return "err:" + state.message;      // message exists only here
    }
}

console.log(render({ status: "idle" }));
console.log(render({ status: "loading" }));
console.log(render({ status: "success", report: { name: "cbc" } }));
console.log(render({ status: "error", message: "rejected" }));

Output:

ready
loading
ok:cbc
err:rejected

The status field is the discriminant, the coloured cap. In the "success" branch the compiler knows state is the success member, so state.report is available; try to read it in the "idle" branch and it is a compile error, because that member has no report. The four calls exercise the four members in turn, printing ready, loading, ok:cbc, and err:rejected. No optional chaining appears anywhere, because there are no optional fields: each shape carries exactly what it needs.


Technical Depth: Literal Discriminants and Exhaustiveness

A union narrows only when the shared field is a literal type in every member. The moment that field widens to string, the cap has no readable colour and narrowing silently stops working.

The discriminant must be a literal

// src/literal.ts
type Sample =
    | { cap: "lavender"; cells: number }
    | { cap: "grey"; glucose: number };

function summarise(sample: Sample): string {
    switch (sample.cap) {
        case "lavender":
            return "cells=" + sample.cells;
        case "grey":
            return "glucose=" + sample.glucose;
    }
}

// A literal is inferred from the annotated shape, so narrowing works
const a: Sample = { cap: "lavender", cells: 5 };
const b: Sample = { cap: "grey", glucose: 90 };

console.log(summarise(a));
console.log(summarise(b));
console.log(a.cells + b.glucose);

Output:

cells=5
glucose=90
95

Because cap is a literal in each member, the switch narrows and each branch sees the right payload: sample.cells in the lavender branch, sample.glucose in the grey branch. The values print cells=5 and glucose=90, and the last line sums 5 + 90 = 95. The classic way to break this by accident is losing literal inference: const action = { cap: "lavender", cells: 5 } infers cap as the wide string, not the literal "lavender", so it is no longer assignable to Sample. Annotating the variable with its union type, as done here, keeps the literal and catches a wrong cap at the declaration.

Exhaustiveness with assertNever

The real payoff is that the compiler can force you to handle every member. An assertNever helper in the default branch turns a newly added member into a compile error.

// src/exhaustive.ts
type Shape =
    | { kind: "circle"; r: number }
    | { kind: "square"; side: number };

function assertNever(value: never): never {
    throw new Error("unhandled: " + JSON.stringify(value));
}

function area(shape: Shape): number {
    switch (shape.kind) {
        case "circle":
            return 3 * shape.r * shape.r;   // integer stand-in for pi
        case "square":
            return shape.side * shape.side;
        default:
            return assertNever(shape);
    }
}

console.log(area({ kind: "circle", r: 10 }));
console.log(area({ kind: "square", side: 6 }));
console.log(area({ kind: "circle", r: 10 }) + area({ kind: "square", side: 6 }));

Output:

300
36
336

In the default branch every known kind has been eliminated, so shape has type never and assertNever(shape) compiles. The circle uses an integer 3 in place of pi purely to keep the arithmetic exact and hand-traceable: 3 * 10 * 10 = 300 and 6 * 6 = 36, summing to 336. If you later add { kind: "triangle"; base: number; height: number } to Shape, the default branch stops compiling, because a triangle shape is not assignable to never, and the error points straight at the switch you forgot to update.

Deriving related types from the union

Once a union exists, the type system can pick it apart so you never restate its labels by hand.

DerivationExpressionYields
all labelsAction indexed by "type"the union of every type string
one memberExtract of Action by a typejust that member's shape
a handler mapkey remap over the membersone entry per member, typed
// src/derive.ts
type Action =
    | { type: "add"; amount: number }
    | { type: "remove"; amount: number }
    | { type: "clear" };

type ActionType = Action["type"];               // "add" | "remove" | "clear"
type AddAction = Extract<Action, { type: "add" }>;   // { type: "add"; amount: number }

function label(action: Action): ActionType {
    return action.type;
}

const only: AddAction = { type: "add", amount: 7 };

console.log(label({ type: "remove", amount: 2 }));
console.log(only.amount);
console.log(only.amount + 1);

Output:

remove
7
8

Action["type"] reads out the union of every discriminant string without you writing them a second time, and Extract<Action, { type: "add" }> pulls out exactly the "add" member so only.amount is available. Printing label(...) gives the discriminant remove, and the extracted member's amount of 7 prints, then 7 + 1 = 8. Every label here is derived from the union rather than duplicated, so adding a member updates ActionType automatically.


Real World Example: A Typed Reducer Over a Sample Queue

A lab's front-desk system holds a queue of accepted samples and applies a stream of actions to it: a sample is added, one is marked done, one is removed, or the queue is cleared. The actions are a discriminated union keyed by type, and a reducer narrows on that field to update the queue immutably. Because the union is exhaustive and the reducer ends in assertNever, a new action type cannot be added without the compiler demanding a branch for it.

// src/reducer.ts
interface Sample {
    id: number;
    done: boolean;
}

interface Queue {
    samples: Sample[];
}

type Action =
    | { type: "added"; id: number }
    | { type: "toggled"; id: number }
    | { type: "removed"; id: number }
    | { type: "cleared" };

function assertNever(value: never): never {
    throw new Error("unhandled: " + JSON.stringify(value));
}

function reducer(state: Queue, action: Action): Queue {
    switch (action.type) {
        case "added":
            return { samples: [...state.samples, { id: action.id, done: false }] };
        case "toggled":
            return {
                samples: state.samples.map((s) =>
                    s.id === action.id ? { id: s.id, done: !s.done } : s
                ),
            };
        case "removed":
            return { samples: state.samples.filter((s) => s.id !== action.id) };
        case "cleared":
            return { samples: [] };
        default:
            return assertNever(action);
    }
}

const actions: Action[] = [
    { type: "added", id: 1 },
    { type: "added", id: 2 },
    { type: "added", id: 3 },
    { type: "toggled", id: 2 },
    { type: "removed", id: 1 },
];

let state: Queue = { samples: [] };
for (const action of actions) {
    state = reducer(state, action);
}

function pad(text: string, width: number): string {
    const gap = width - text.length;
    return text + " ".repeat(gap > 0 ? gap : 0);
}

let doneCount = 0;
console.log("samples: " + state.samples.length);
console.log(pad("ID", 6) + "DONE");
for (const s of state.samples) {
    if (s.done) {
        doneCount++;
    }
    console.log(pad(String(s.id), 6) + s.done);
}
console.log("done: " + doneCount + "/" + state.samples.length);

Output:

samples: 2
ID    DONE
2     true
3     false
done: 1/2

Trace the five actions against a queue that starts empty. The three added actions append samples 1, 2, and 3, all not done. The toggled action for id 2 flips that sample's done to true. The removed action for id 1 drops sample 1 from the queue. What remains, in insertion order, is sample 2 (done) and sample 3 (not done), so the report shows two samples with 2 marked true and 3 marked false, and done: 1/2. Every branch of the reducer builds a fresh Queue rather than mutating the old one, and the discriminant makes action.id available in exactly the three branches that carry it.

The value of the union here is that dispatch-style calls are fully checked: reducer(state, { type: "toggled" }) fails because id is missing, and reducer(state, { type: "added", done: true }) fails because done is not part of the added member. The assertNever default means that adding, say, a { type: "filtered"; ... } member forces a new branch or the file will not compile, so the queue logic and the action set stay locked together.

That design still has a genuine flaw worth naming. The reducer trusts every id blindly: toggled and removed search by id and simply do nothing when no sample matches, so a toggled action for an id that was never added, or was already removed, passes silently with no error and no effect, which hides upstream bugs that send stale ids. A stricter design would surface a miss rather than swallow it. Two smaller limits sit alongside: added does not guard against a duplicate id, so two added actions with the same id create two indistinguishable samples the later toggled cannot tell apart; and the model keys everything on a client-supplied id with no generation of its own, so correctness depends entirely on the caller never reusing a number.


Common Mistakes

  1. Using a non-literal discriminant. A field typed string rather than a specific literal carries no code the compiler can read, so narrowing over it silently does nothing.
  2. Letting literal inference widen on assignment. const a = { kind: "add" } infers kind as string; annotate the variable with its union type or use as const to keep the literal.
  3. Modelling state as a bag of optional fields. Four independent optionals imply sixteen combinations, most of them invalid, where a union of shapes admits only the valid ones.
  4. Naming the discriminant differently across members. If one member uses type and another uses kind, there is no shared field to narrow on and the union is not discriminated.
  5. Omitting an exhaustiveness check. Without an assertNever default, adding a member silently skips the new case at runtime instead of failing to compile.
  6. Reaching for if/else chains over a union. A switch on the discriminant pairs naturally with assertNever, which an if/else ladder cannot give you cleanly.
  7. Hoisting payload fields to the top as optionals. Keeping data and message as optional top-level fields recreates the very ambiguity the union was meant to remove.
  8. Trusting ids without checking membership. A reducer that searches by id and does nothing on a miss hides stale-id bugs; decide deliberately whether a miss is a no-op or an error.
  9. Building a class hierarchy where a union of plain objects would do. Plain object unions serialise, compare, and narrow more predictably than classes for discriminated state.

Best Practices

  • Use one consistently named discriminant per domain. Settle on type for actions, status for async state, and kind for domain variants so narrowing reads the same everywhere.
  • Model state as a union of valid shapes. Make invalid combinations unrepresentable rather than merely discouraged by a comment.
  • End every switch over a union with default: return assertNever(x). It converts a forgotten member from a runtime skip into a compile error.
  • Derive related types instead of duplicating literals. Reach for the indexed access on the discriminant and Extract rather than restating the label union by hand.
  • Annotate variables that hold union members. A type annotation at the declaration stops literal widening at the source, before it reaches a call site.
  • Keep payload fields on the member that owns them. A field belongs to the one shape that needs it, never hoisted to the top as an optional shared by all.
  • Prefer past-tense event names for actions. Names like "added" and "toggled" describe what happened, which reads better than imperative command names.
  • Decide explicitly what a lookup miss means. When a reducer acts on an id, choose deliberately between a silent no-op and a surfaced error rather than defaulting to silence.

Practice Exercises

  1. The Labels. Convert { loading?: boolean; data?: Post[]; error?: string } into a four-member discriminated union keyed by status, and rewrite a render function so no optional chaining appears anywhere.
  2. The Missing Case. Build a Shape union of three members with an assertNever default, then add a fourth member and read the exact compile error the default branch produces.
  3. The Derived Labels. Take a five-member Action union and derive both its label union with indexed access and one member with Extract, then confirm adding a member updates the label union with no other edit.
  4. The Strict Reducer. Extend the sample-queue reducer so a toggled or removed action for an unknown id is surfaced rather than silently ignored, and show the change with an action carrying an id that is not in the queue.