Sub topic 11
Exhaustive checks with assertNever
This chapter assumes you can write discriminated unions and switch statements, and that you know never is the type with no values. Here you will use never to make the compiler tell you when a union has a member your code does not handle.
The problem: a switch that silently falls through
Suppose you model shapes as a union and compute areas with a switch.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function areaUnsafe(shape: Shape): number | undefined {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
}
}This compiles. Months later someone adds { kind: "triangle"; ... } to Shape. Nothing in areaUnsafe changes, nothing fails to compile, and triangles now return undefined at runtime. The bug appears far from the edit that caused it.
You want the opposite: adding a member to the union should produce a compile error at every place that must handle it. That is what an exhaustiveness check does.
Why never makes this work
Inside a switch on a discriminant, TypeScript narrows the variable in each case. Each handled case removes one member from the union. After all cases, the remaining type is what is left over. If every member was handled, nothing is left, and the leftover type is never.
Only never is assignable to never. So if you pass the leftover value to a function whose parameter is never, the call compiles only when the leftover is never. Any remaining member makes the argument unassignable, and the compiler reports an error.
The assertNever helper
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function assertNever(x: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(x)}`);
}
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
default:
return assertNever(shape);
}
}
console.log(area({ kind: "square", size: 3 })); // 9The helper does two jobs, one at each stage:
- Compile time: the
neverparameter rejects any argument that is notnever. - Runtime: if a bad value reaches the function anyway, it throws instead of returning garbage.
The return type never lets return assertNever(shape) satisfy the number return type of area, because a function that never returns normally is assignable to any return type.
What happens when the union grows
Now add a triangle and leave area alone:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "triangle"; base: number; height: number };The default branch of area now receives the triangle member, and tsc reports an error on the assertNever(shape) call:
Argument of type '{ kind: "triangle"; base: number; height: number; }'
is not assignable to parameter of type 'never'.The message names the exact unhandled member. You fix it by adding the case:
case "triangle":
return (shape.base * shape.height) / 2;The error disappears because the default branch is never again.
Variants of the same idea
You do not need a helper function for every situation. The mechanism is always "assign the leftover to never".
Inline never assignment
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.size;
case "triangle":
throw new Error("not implemented");
default: {
const unreachable: never = shape;
throw new Error(`Unexpected: ${JSON.stringify(unreachable)}`);
}
}
}This avoids a shared helper, but you repeat the throw. The helper keeps the error message consistent across the codebase.
if/else chains and literal unions
Exhaustiveness is not limited to objects with a kind field. Any union that narrows works, including string literal unions.
type Status = "idle" | "loading" | "done";
function assertNever(x: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(x)}`);
}
function statusLabel(status: Status): string {
if (status === "idle") return "Waiting";
if (status === "loading") return "Working";
if (status === "done") return "Finished";
return assertNever(status);
}Each failed if removes one literal from the union, so status is never at the final line.
Switch without a default
If a function declares a non-undefined return type, you can leave out the default branch. When every member is handled, TypeScript knows the end of the function is unreachable. When a member is missing, it reports error 2366, "Function lacks ending return statement and return type does not include 'undefined'". This needs strictNullChecks, which strict enables. It catches the same mistake, but it adds no runtime guard, so a bad value silently yields undefined.
Exhaustive lookup tables
A Record over the discriminant types gives the same guarantee for data instead of control flow:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
const shapeNames: Record<Shape["kind"], string> = {
circle: "Circle",
square: "Square",
};Adding a member to Shape makes this object literal fail with a "property is missing" error until you add the new key.
| Technique | Compile-time check | Runtime guard | Best for |
|---|---|---|---|
| `assertNever(x)` in default | Yes | Throws | Functions that branch on a union |
| `const _: never = x` | Yes | Only if you add a throw | One-off checks without a helper |
| No default, declared return type | Yes (error 2366) | No | Small functions returning a value |
| `Record<Union, T>` | Yes | No | Lookup tables keyed by a union |
Edge cases and gotchas
any in the input defeats the check
If the value is any, narrowing never produces never. The default branch sees any, which is assignable to never, so assertNever compiles even with no cases at all.
function broken(shape: any): number {
switch (shape.kind) {
default:
return assertNever(shape); // compiles: any is assignable to never
}
}An exhaustiveness check is only as strong as the type feeding it. Type the parameter as the union, not any.
Widened types never narrow to never
If the discriminant is string instead of a literal union, handling a few cases leaves string, not never. You must declare the union (or use as const on the source of values) for the check to work.
Optional and nullable members count
Shape | undefined leaves undefined in the default branch if you do not handle it. That is correct behavior: the compiler is telling you a case is missing. Handle it before the switch or add it as a case.
A catch-all default hides the problem
A default: return 0; makes the code compile when a member is added. The check works only if the default branch demands never. Reserve defaults for cases where a fallback is a deliberate design choice.
Runtime data can still violate the type
assertNever proves your code is exhaustive for the declared type. It does not prove the incoming data matches that type. A payload parsed from JSON may carry kind: "hexagon", which your types never described. If you cast such data with as Shape, the check passes at compile time and throws at runtime. Validate external data first, as covered in the chapter on unknown at trust boundaries. The runtime throw in assertNever is a last line of defense, not a validator.
Serializing the message can fail
JSON.stringify returns undefined for undefined and functions, and it throws on circular references and on BigInt. For values that might be unusual, build the message more defensively, for example with String(x) inside a try. For plain data unions, JSON.stringify is fine.
Putting it together
The workflow has three steps:
- Model the alternatives as a union with a literal discriminant, such as
kind. - Handle each member with its own
caseorif. - End with
assertNever(value)so the compiler checks that nothing is left.
When the union later changes, tsc lists every function that needs a new case. You find the places by compiling, not by searching the code.
Exercise
You have type Level = "debug" | "info" | "warn" and a function color(level: Level): string that uses if (level === "debug") ... and if (level === "info") ..., then ends with return assertNever(level);. It compiles with an error. What does the error say about the argument, and what is the fix?
Show answer
At the final line, level has been narrowed only by the debug and info checks, so its type is "warn". The error says that the argument of type "warn" is not assignable to parameter of type never. The fix is to add if (level === "warn") return ...; before the assertNever call, which leaves level as never.
Exercise
A teammate writes function area(shape: any): number { switch (shape.kind) { case "circle": return 1; default: return assertNever(shape); } }. It compiles even though square is unhandled. Why, and how do you make the check meaningful?
Show answer
Because shape is any, narrowing never removes anything and any is assignable to never, so assertNever(shape) compiles. Change the parameter type to the Shape union. Then the default branch receives the unhandled square member, and the call fails to compile until the case is added.