Sub topic 7
Exhaustiveness checking with never
This chapter assumes you can write a discriminated union and narrow it with switch. It also assumes strict: true is set in tsconfig.json. Here you will learn how the compiler can prove that every variant is handled, and how to make a forgotten case fail the build.
The problem: silent gaps
Take the Shape union from the earlier chapters:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };Months later, someone adds a triangle variant. Every function that switches on shape.kind now has a gap. Nothing in plain JavaScript warns you. At runtime, the function falls through the switch and returns undefined. That value then spreads through your program as a NaN or a blank label.
Exhaustiveness checking moves this failure from runtime to compile time. The compiler tells you which functions need an update.
What never means
never is the type with no values. No expression can have a value of type never at runtime. Two facts make it useful here:
- Nothing except
neveritself is assignable tonever. - Narrowing removes a member from a union each time a check rules it out.
Inside a switch, each case removes one variant from the type of the switched value. If every variant is handled, nothing is left, and the remaining type is never. If one variant is missing, that variant remains, and it is not assignable to never.
The assertNever helper
The standard technique passes the leftover value to a function that only accepts never:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.size;
case "rectangle":
return 2 * (shape.width + shape.height);
default:
return assertNever(shape);
}
}
console.log(perimeter({ kind: "square", size: 2 }));In the default branch, shape has had all three variants removed, so its type is never. The call type-checks.
Now add a variant:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number }
| { kind: "triangle"; base: number; height: number };In perimeter, the default branch now sees shape as { kind: "triangle"; ... }. The compiler reports an error similar to this:
Argument of type '{ kind: "triangle"; base: number; height: number; }'
is not assignable to parameter of type 'never'.The error points at the exact line that needs a new case. The compiler also names the missing variant in the message.
The helper has two jobs:
- At compile time, its
neverparameter rejects any leftover variant. - At runtime, it throws if a value of the wrong shape arrives anyway, for example from unvalidated JSON.
Exhaustiveness through the return type
You do not always need a helper. If a function declares a return type that does not include undefined, and strict is on, the compiler checks that every path returns a value. The area function from the earlier chapter relies on this:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
}
}
console.log(area({ kind: "circle", radius: 1 }));If you add a triangle variant and forget a case, TypeScript reports Function lacks ending return statement and return type does not include 'undefined'. This check is free, but it has limits:
- It only works for functions that return a value. A function that returns
voidor performs side effects has no return to check. - The message does not name the missing variant.
- It fails to protect you if the return type includes
undefinedor if you use anifchain that ends with a different fallback.
For those reasons, many teams use assertNever as an explicit marker even when the return type check would also catch the problem.
Exhaustiveness without a default branch
You can place the check after the switch instead of in a default branch:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
function label(shape: Shape): string {
switch (shape.kind) {
case "circle":
return "round";
case "square":
return "boxy";
}
return assertNever(shape);
}
console.log(label({ kind: "circle", radius: 3 }));After the switch, the compiler knows that every case returned, so shape is never. Both placements behave the same. Pick one and use it consistently across the codebase.
Using a never variable instead of a function
You can also write the check as an assignment:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function describe(shape: Shape): string {
switch (shape.kind) {
case "circle":
return "circle";
case "square":
return "square";
default: {
const unreachable: never = shape;
return unreachable;
}
}
}
console.log(describe({ kind: "square", size: 1 }));This produces the same compile error when a variant is missing. It adds no runtime throw, so the helper function is usually the safer choice. A throw gives you a clear failure if bad data ever reaches the branch.
Exhaustiveness with if chains
The same narrowing works with if and else if. The final else receives whatever is left:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
function name(shape: Shape): string {
if (shape.kind === "circle") {
return "Circle";
} else if (shape.kind === "square") {
return "Square";
} else if (shape.kind === "rectangle") {
return "Rectangle";
} else {
return assertNever(shape);
}
}
console.log(name({ kind: "rectangle", width: 2, height: 3 }));A switch is easier to scan when there are more than two or three variants. An if chain is fine for two.
Edge cases and failure modes
Grouped cases
Several cases can share one branch. The check still works, because each listed value is removed from the union:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function isPolygon(shape: Shape): boolean {
switch (shape.kind) {
case "square":
case "rectangle":
return true;
case "circle":
return false;
}
}
console.log(isPolygon({ kind: "circle", radius: 1 }));A catch-all default hides the gap
The most common way to lose exhaustiveness is a default branch that returns a fallback value:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function sides(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 0;
default:
return 4;
}
}
console.log(sides({ kind: "square", size: 1 }));This compiles today. When someone adds a triangle variant, it silently falls into default and reports four sides. The compiler has no complaint, because default accepts everything. Reserve default for assertNever, or list every case explicitly.
Non-union values at runtime
The compiler guarantees exhaustiveness only for values that really have the declared type. If JSON.parse or a network response delivers { kind: "hexagon" }, the static check cannot see it. The throw in assertNever is your runtime backstop. A later chapter covers validating such data before it enters your program.
Compiler options and linters
The never check needs strict (specifically strictNullChecks) to work reliably. Some projects also enable the @typescript-eslint/switch-exhaustiveness-check lint rule. It reports an incomplete switch even when no assertNever is present, which helps in functions that return void.
Choosing a technique
| Technique | Catches a missing case at compile time | Names the missing variant | Throws at runtime on bad data |
|---|---|---|---|
| Return type check only | Yes, when the function returns a value | No | No, returns `undefined` |
| `assertNever(shape)` | Yes | Yes | Yes |
| `const x: never = shape` | Yes | Yes | No |
| `default` with a fallback value | No | No | No |
Summary
neveris the type left after every variant has been ruled out.- Passing the leftover value to a function that takes
nevermakes a forgotten case a compile error. - The error message names the variant you have not yet handled.
- A fallback
defaultreturning a real value defeats the check. - The compiler cannot see bad data at runtime, so the helper also throws.
Exercise
A teammate writes function sides(shape: Shape): number with a switch that handles circle and square, and a default: return 4. You then add a triangle variant to Shape. Does the compiler report an error? How would you change the function so that it does, and what would the compiler then report?
Show answer
No error is reported, because default accepts the new triangle variant and returns 4. Replace the default branch with an explicit case "triangle": return 3; and a default: return assertNever(shape);. If you add the variant but skip its case, the compiler reports that the triangle object type is not assignable to the parameter of type never, which points you to the missing case.
Exercise
Why does assertNever both take a never parameter and throw an error, instead of only doing one of those?
Show answer
The never parameter makes the compiler reject any call where a variant is still left over, which gives the compile-time check. The throw covers values that the type system cannot see, such as unvalidated JSON with an unknown kind, so the program fails loudly instead of continuing with a wrong result.