Intermediate · 5 of 16 · 16 min read
Discriminated unions
The single most useful pattern in TypeScript — one literal property that lets the compiler tell the branches apart, and makes impossible states impossible.
- Discriminated unions
A discriminated union is a union of object types that all share one property, and where that property has a different literal type in each member. That one detail lets a single comparison narrow the whole object — and lets you build types that cannot represent a nonsense state.
The shape
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "rect"; width: number; height: number };
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;
}
}
console.log(area({ kind: "rect", width: 2, height: 3 })); // 6
Inside each case the object is fully narrowed: shape.radius exists in the first and nowhere
else. Without the discriminant, only the shared properties would be readable and every branch
would need an in check or a custom guard.
The property can be called anything — kind, type, status, tag — and can be any literal
type, including a number or a boolean:
type Result =
| { ok: true; value: string }
| { ok: false; error: Error };
function render(result: Result) {
return result.ok ? result.value.toUpperCase() : result.error.message;
}
console.log(render({ ok: true, value: "hi" })); // "HI"
It must be a literal
type Bad =
| { kind: string; radius: number }
| { kind: string; side: number };
declare const shape: Bad;
if (shape.kind === "circle") {
// shape.radius; // Property 'radius' does not exist on type 'Bad'
}
Comparing a string to "circle" eliminates nothing, because both members could hold that value.
The same mistake appears from the value side, through widening:
type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };
const widened = { kind: "circle", radius: 1 }; // kind: string
// const s: Shape = widened; // not assignable
const exact = { kind: "circle", radius: 1 } as const;
const s: Shape = exact; // fine
console.log(s.kind);
Making impossible states impossible
This is the argument that wins people over. Compare two ways to model a request:
// Four representable states, two of them nonsense:
interface Loose<T> {
loading: boolean;
data?: T;
error?: Error;
}
// { loading: true, data: x, error: e } — what does that mean?
// { loading: false } — and that?
// Exactly three states, all meaningful:
type Request<T> =
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
The consequence shows up at every consumer. With the loose version, every reader has to check two properties and handle combinations that cannot occur:
type Request<T> =
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function render(request: Request<string>): string {
switch (request.status) {
case "loading": return "…";
case "success": return request.data.toUpperCase(); // guaranteed present
case "error": return request.error.message; // guaranteed present
}
}
console.log(render({ status: "success", data: "ok" })); // "OK"
No optional chaining, no “this should never happen” branch, no defensive ??. The type did the
work.
| Optional properties | Discriminated union | |
|---|---|---|
| Representable states | 2ⁿ | exactly the ones you listed |
| Accessing the payload | data?.name |
data.name, guaranteed |
| Forgetting a case | silent | a compile error, with the check below |
| Adding a state | touches nothing, breaks everything | breaks the build where it must |
Exhaustiveness
When every member has been handled, the remaining type is never. Assigning that to a never
parameter turns a newly added member into a compile error:
type Shape = { kind: "circle" } | { kind: "square" };
function assertNever(value: never): never {
throw new Error(`unhandled: ${JSON.stringify(value)}`);
}
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return 1;
case "square": return 2;
default: return assertNever(shape);
}
}
console.log(area({ kind: "circle" })); // 1
// Adding `| { kind: "triangle" }` to Shape makes the default line fail:
// Argument of type '{ kind: "triangle" }' is not assignable to parameter of type 'never'
A return-type annotation does the same job more quietly — without one, the function’s inferred
return type simply widens to include undefined and nothing complains:
type Shape = { kind: "circle" } | { kind: "square" };
function area(shape: Shape): number { // the annotation is what forces the check
if (shape.kind === "circle") return 1;
if (shape.kind === "square") return 2;
// Function lacks ending return statement, once a third kind exists
throw new Error("unreachable");
}
console.log(area({ kind: "square" }));
Working with one member
Extract names a branch without writing the shape again:
type Request =
| { status: "loading" }
| { status: "success"; data: string }
| { status: "error"; error: Error };
type Success = Extract<Request, { status: "success" }>; // the whole member
type NotLoading = Exclude<Request, { status: "loading" }>;
function handle(request: Success) { return request.data; }
const ok: Success = { status: "success", data: "x" };
console.log(handle(ok));
// A helper worth having for any such union:
type ByStatus<S extends Request["status"]> = Extract<Request, { status: S }>;
const failed: ByStatus<"error"> = { status: "error", error: new Error("no") };
console.log(failed.error.message);
Where they turn up
Almost everywhere, once you start noticing:
// A reducer action
type Action =
| { type: "add"; item: string }
| { type: "remove"; id: number }
| { type: "clear" };
// A parse result, instead of throwing
type Parsed<T> = { ok: true; value: T } | { ok: false; issues: string[] };
// A protocol message
type Message =
| { type: "ping" }
| { type: "data"; payload: unknown }
| { type: "close"; code: number };
function reduce(items: string[], action: Action): string[] {
switch (action.type) {
case "add": return [...items, action.item];
case "remove": return items.filter((_, i) => i !== action.id);
case "clear": return [];
}
}
console.log(reduce(["a"], { type: "add", item: "b" })); // ["a", "b"]
Common mistakes
A discriminant that is not a literal
Mistake. type: string on every member.
Why it fails. Comparing it narrows nothing, so the payload stays unreachable.
What to do instead. A distinct string literal per member — and as const on any object
literal you build before assigning it.
Optional properties instead of a union
Mistake. { loading: boolean; data?: T; error?: Error }.
Why it fails. It permits states that cannot occur, so every consumer writes checks for them —
and still has to use ?. on data that is definitely present.
What to do instead. List the real states and give each the payload it actually has.
A default branch that silently swallows a new member
Mistake. default: return "unknown".
Why it fails. Adding a member compiles cleanly and quietly takes the default, which is the
bug the union was supposed to prevent.
What to do instead. default: return assertNever(value), or no default at all with an
annotated return type.
Check yourself
4 questions from the bank on what you just read. Answering here does not affect your quiz history.
What makes a union *discriminated*?
In the branch where every member has been handled, the value has no type left.
What is the type of shape in the default branch?
type Shape = { kind: "circle" } | { kind: "square" };
function area(shape: Shape) {
switch (shape.kind) {
case "circle": return 1;
case "square": return 2;
default: return shape;
}
}Why model an API result as a discriminated union instead of { data?: T; error?: Error }?
The discriminant has to be a literal type, not a widened one.
Why does narrowing fail on this union?
type Circle = { kind: string; radius: number };
type Square = { kind: string; side: number };
function area(shape: Circle | Square) {
if (shape.kind === "circle") {
return shape.radius;
}
return 0;
}Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.