Sub topic 6
Exhaustiveness checking with never
A union is only safe to branch on if every branch is handled. This chapter shows how to make the compiler check that. When you add a new member to a union, every place that handles the union and forgot the new member becomes a compile error.
Prerequisites
This chapter assumes you can read these:
- Union types and literal unions, such as
"north" | "south". - Narrowing with
typeof,in, and equality checks. - Discriminated unions, where each member has a shared tag property such as
kind. - Function return type annotations.
Compile with "strict": true in tsconfig.json. Several behaviors below depend on strictNullChecks.
The problem: silent gaps
Suppose you model shapes as a discriminated union and write a function that handles each one:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
return shape.size ** 2;
}This works today. Later someone adds { kind: "triangle"; base: number; height: number } to Shape. The function still compiles, because the final return is reached by the new member too. shape.size is then undefined, and area returns NaN for every triangle. The compiler had the information to catch this, but nothing asked it to.
Exhaustiveness checking asks it to.
The working model: what never means after narrowing
never is the type with no values. Narrowing removes types from a union as each check rules them out:
- Before any check,
shapeisCircle | Square. - After
case "circle"returns, the remaining type isSquare. - After
case "square"returns, nothing remains, so the type isnever.
If every member has been handled, the variable reaches the end of the switch typed as never. If a member is unhandled, the variable still has that member's type. Only never can be assigned to never. So assigning the leftover value to a never variable compiles when you handled everything and fails when you didn't.
The assign-to-never pattern
Here is the pattern with the default branch doing the check:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
default: {
const unreachable: never = shape;
return unreachable;
}
}
}With only circle and square in the union, shape in the default branch is never, so the code compiles. Now add the triangle to Shape without touching area. The default branch now sees shape as the triangle type, and the compiler reports an error on the assignment:
Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'.The error appears in area, not at the place where you edited the union. That is the point. The compiler lists every function you need to update.
The braces around the default body keep unreachable scoped to that branch, so several switches in one function can reuse the name.
A reusable assertNever helper
Writing the never variable each time is noisy. Most codebases use a small helper:
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "triangle"; base: 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 "triangle":
return (shape.base * shape.height) / 2;
default:
return assertNever(shape);
}
}
console.log(area({ kind: "triangle", base: 4, height: 3 })); // 6The helper does two jobs.
- Compile time. The parameter type is
never, so passing anything else is an error. If you remove thetrianglecase, the callassertNever(shape)fails with the same "not assignable to never" message. - Run time. The function throws. Types describe what you expect, but data from JSON, an API, or a
ascast can still carry akindthe type doesn't list. Without the throw,areawould returnundefinedfor such a value and the bug would surface later and far from its cause.
The return type never lets return assertNever(shape) satisfy a function that must return number.
Exhaustiveness without a default branch
A switch over a union doesn't need a default. If the function declares a return type that does not include undefined, the compiler checks that every path returns:
type Direction = "north" | "south" | "east" | "west";
function turnAround(d: Direction): Direction {
switch (d) {
case "north": return "south";
case "south": return "north";
case "east": return "west";
case "west": return "east";
}
}If you add "up" to Direction and leave turnAround alone, the compiler reports error TS2366: Function lacks ending return statement and return type does not include 'undefined'. The compiler knows the switch is exhaustive only when d is never after the last case. Any remaining member means control can fall out of the function.
This form has two limits.
- It only works for functions that return a value. A
voidfunction that does side effects gives no error when a case is missing. - The error message is less direct than the
neverassignment, because it points at the function rather than at the missing member.
Use the explicit never check when you want the error to name the unhandled type, and when you want a runtime throw as well.
Newer syntax: satisfies never
Since TypeScript 4.9 you can write the check as an expression with satisfies:
type Light = "red" | "yellow" | "green";
function next(light: Light): Light {
switch (light) {
case "red":
return "green";
case "green":
return "yellow";
case "yellow":
return "red";
default:
light satisfies never;
throw new Error("Unhandled light");
}
}light satisfies never fails to compile when light is anything other than never. It avoids the extra variable, but it is only a compile-time check, so you still write the throw yourself.
Common errors and gotchas
The check silently passes when the value is any
If shape is typed any, every assignment compiles, including const x: never = shape. This happens with untyped JSON.parse results and with loosely typed libraries. Parse or validate the data into the union type at the boundary, then switch on the typed value.
Casts hide the missing case
Writing data as Shape tells the compiler to trust you. The exhaustiveness check then protects only the type, not the real data. The assertNever throw is your runtime backstop.
The discriminant must be narrowable
Narrowing by switch (shape.kind) works because kind is a literal type in each member. If one member declares kind: string, the tag is no longer a unique literal, narrowing stops removing members, and the leftover type will not shrink to never. The compiler then reports an error in a place where you believe everything is handled. Fix the tag type, not the check.
Destructuring loses the link in older code
If you destructure const { kind } = shape and switch on kind, the compiler has narrowed kind but not shape in older versions of TypeScript. Switch on shape.kind directly so that shape itself narrows. Newer versions handle some destructured cases, but switching on the property is the portable choice.
A catch-all default defeats the check
This version never fails to compile:
function areaLoose(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
default:
return 0;
}
}The default accepts any leftover member, so new shapes quietly return 0. If you want exhaustiveness, the default branch must either call assertNever or be absent.
Linters can enforce it as well
The typescript-eslint rule switch-exhaustiveness-check reports a switch on a union that is missing cases. It is useful where the never pattern is easy to forget, such as a void function that has no return type to check.
Choosing a form
| Situation | Suggested form |
|---|---|
| Function returns a value, small union | `switch` with no `default` and a return type |
| You want the error to name the missing member | `default` with `assertNever` |
| Data may come from outside the type system | `assertNever` with its runtime `throw` |
| `void` function or side effects only | `assertNever` or the lint rule |
| You deliberately want a fallback value | Plain `default`, and accept no checking |
Exercises
Exercise
A function handles a union with if and else if branches for every member except the last one, and then ends with const check: never = value;. What is the type of value at that line when all members are handled, and what happens at compile time if one member is not handled?
Show answer
When every member has been ruled out by earlier checks, narrowing leaves value as never, so the assignment compiles. If one member is not handled, value still has that member's type at that line, and the assignment fails with an error such as "Type 'X' is not assignable to type 'never'". The error points at the function that is missing the case.
Exercise
Why does assertNever both declare its parameter as never and throw an error? What does each of these do?
Show answer
The never parameter makes the call a compile-time exhaustiveness check, because only a value that has been narrowed to never can be passed. The throw covers run time. Data that comes from JSON, an API, or a type cast can carry a value the type does not list, and the throw reports it immediately instead of letting the function return undefined or a wrong result.
Exercise
You add "up" to type Direction = "north" | "south" | "east" | "west". The function turnAround(d: Direction): Direction has a switch with four cases and no default. Does it still compile? Why or why not?
Show answer
No. After the four cases, d is still "up" rather than never, so control can leave the switch without a return. Because the declared return type does not include undefined, the compiler reports TS2366: "Function lacks ending return statement and return type does not include 'undefined'".