Discriminated unions
One literal tag
A discriminated union is a union where every member carries the same tag field with a different literal value. The tag tells TypeScript which shape it is looking at.
Here Circle and Square share the kind field, so Shape is either a circle or a square and nothing else.
type Circle = { kind: "circle"; radius: number; }; type Square = { kind: "square"; size: number; }; type Shape = Circle | Square;
Switch on the tag
Narrowing means TypeScript shrinks the union after you test the tag. Inside each case branch only the matching member remains, so its own fields are safe to read.
Checking shape.kind once is enough for the whole switch body, and the const box at the end proves the call returns 16.
type Circle = { kind: "circle"; radius: number; }; type Square = { kind: "square"; size: number; }; type Shape = Circle | Square; function area(shape: Shape): number { switch (shape.kind) { case "circle": return 3.14 * shape.radius * shape.radius; case "square": return shape.size * shape.size; } } const box: Shape = { kind: "square", size: 4 }; console.log(area(box));
16
Never miss a case
A switch that forgets a member is a classic bug. The assertNever helper turns a forgotten case into a compile error instead of a silent wrong answer.
In the default branch shape has type never when every case is covered. If a new member is added later, shape stops being never and the compiler points at the exact line to fix.
type Circle = { kind: "circle"; radius: number }; type Square = { kind: "square"; size: number }; type Shape = Circle | Square; function assertNever(value: never): never { throw new Error("Unknown shape"); } function total(shape: Shape): number { switch (shape.kind) { case "circle": return 3.14 * shape.radius * shape.radius; case "square": return shape.size * shape.size; default: return assertNever(shape); } } const plate: Shape = { kind: "circle", radius: 2 }; console.log(total(plate));
12.56
Shape API responses
API responses fit the same pattern perfectly. Success and failure share a status tag, so the reader always knows which fields exist.
Test res.status once and TypeScript narrows res for you. No casts and no guessing about missing fields.
type ApiOk = { status: "ok"; items: string[]; }; type ApiFail = { status: "error"; message: string; }; type ApiResult = ApiOk | ApiFail; function show(res: ApiResult): string { if (res.status === "ok") { return res.items.join(", "); } return res.message; } console.log(show({ status: "ok", items: ["a", "b"] })); console.log(show({ status: "error", message: "down" }));
a, b
down
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What makes a union a discriminated union?
Answer
A shared tag field whose type is a different literal in each member
The literal tag lets the compiler tell the members apart and narrow the union.
-
What does checking
shape.kindinside aswitchdo?Answer
It shrinks the union to the member that matches the case
Each case narrows the union, so the fields of the matching member are safe to read.
-
What does an
assertNeverhelper do for a forgotten member?Answer
It turns the forgotten member into a compile error
The default branch receives a value typed never only when every member is handled.
-
Why is
shapeof typeneverin the default branch of a complete switch?Answer
The compiler knows that no member is left
Every case removed one member, so the remaining union is empty and becomes never.
-
What does this program print?
type Circle = { kind: "circle"; radius: number }; type Square = { kind: "square"; size: number }; type Shape = Circle | Square; function area(shape: Shape): number { switch (shape.kind) { case "circle": return 3.14 * shape.radius * shape.radius; case "square": return shape.size * shape.size; } } const box: Shape = { kind: "square", size: 4 }; console.log(area(box));Answer
16
The square branch multiplies the size by itself, and 4 times 4 is 16.
-
What does this program print?
type Circle = { kind: "circle"; radius: number }; type Square = { kind: "square"; size: number }; type Shape = Circle | Square; function area(shape: Shape): number { switch (shape.kind) { case "circle": return 3.14 * shape.radius * shape.radius; case "square": return shape.size * shape.size; } } console.log(area({ kind: "circle", radius: 2 }));Answer
12.56
The circle branch uses 3.14 times 2 times 2, which is 12.56.
-
What does this program print?
type Circle = { kind: "circle"; radius: number }; type Square = { kind: "square"; size: number }; type Shape = Circle | Square; function total(shape: Shape): number { switch (shape.kind) { case "circle": return 3.14 * shape.radius * shape.radius; case "square": return shape.size * shape.size; default: throw new Error("Unknown shape"); } } console.log(total({ kind: "square", size: 3 }));Answer
9
The square branch multiplies 3 by 3, and the default branch never runs.
-
What does this program print?
type ApiOk = { status: "ok"; items: string[] }; type ApiFail = { status: "error"; message: string }; type ApiResult = ApiOk | ApiFail; function show(res: ApiResult): string { if (res.status === "ok") { return res.items.join(", "); } return res.message; } console.log(show({ status: "ok", items: ["a", "b"] })); console.log(show({ status: "error", message: "down" }));Answer
a, b / down
The ok response joins its items with a comma, and the error response returns its message.
-
What does the compiler say about this program?
type Circle = { kind: "circle"; radius: number }; type Square = { kind: "square"; size: number }; type Shape = Circle | Square; function area(shape: Shape): number { if (shape.kind === "circle") { return shape.size; } return shape.size * shape.size; } console.log(area({ kind: "square", size: 2 }));Answer
error TS2339: Property 'size' does not exist on type 'Circle'.
The circle branch narrows the value to Circle, which has a radius and no size field.
-
What does the compiler say about this program?
type Circle = { kind: "circle"; radius: number }; type Square = { kind: "square"; size: number }; type Shape = Circle | Square; const bad: Shape = { kind: "triangle", size: 3 }; console.log(bad);Answer
error TS2322: Type '"triangle"' is not assignable to type '"square" | "circle"'.
No member accepts the tag triangle, so the literal fails against the two allowed tags.
Article author: Arthur Isaev