Sub topic 9
Exhaustiveness checking with never
This chapter assumes you can write union types and type aliases, and that you have used switch over a discriminated union. You should know that narrowing removes members from a union as checks rule them out. Here you will use that fact to make the compiler tell you when a union member has no handler.
The problem: silent gaps when a union grows
A discriminated union lists every variant a value can take. Code that handles each variant is correct today. When someone adds a variant later, that code is wrong, and nothing warns you unless you ask the compiler to.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function areaUnchecked(shape: Shape): number | undefined {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
}
}Suppose you add { kind: "triangle"; base: number; height: number } to Shape. This function still compiles. At runtime a triangle falls out of the switch and the function returns undefined. The return type had to be widened to admit that case, which hides the gap from callers. The goal is for the compiler to refuse to build until every variant is handled.
What never means
never is the type with no values. No expression can produce a value of type never at runtime, so nothing is assignable to it except never itself. It appears in three places:
- A function that never returns normally has return type
never, for example one that always throws. - An impossible intersection, such as
string & number, reduces tonever. - A narrowed variable has type
neverwhen every member of its union has been ruled out.
The third case is the one that matters here. Every case removes one member from the type of shape. After all cases, nothing is left.
The never assignment pattern
In the default branch, assign the remaining value to a variable annotated as never. If narrowing has removed every member, the assignment is legal. If any member remains, the compiler reports an error, because that member is not assignable to never.
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;
}
}
}Now add the triangle variant to Shape and leave area alone. In the default branch, shape has type { kind: "triangle"; base: number; height: number }. The line const unreachable: never = shape fails with an error like Type '{ kind: "triangle"; ... }' is not assignable to type 'never'. The error points at the exact function that needs a new case, and the code does not build until you add it.
The braces around the default body create a block scope. Without them, a second switch in the same function that declares unreachable would collide with it.
A reusable helper
Repeating the assignment in every switch is noisy. A small helper function makes the intent clearer and can also fail loudly at runtime.
function assertNever(value: never): never {
throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);
}
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function perimeter(shape: Shape): number {
switch (shape.kind) {
case "circle":
return 2 * Math.PI * shape.radius;
case "square":
return 4 * shape.size;
default:
return assertNever(shape);
}
}The parameter type never makes the call a compile-time check. Passing a leftover variant is an error, so you get the same protection as the assignment. The thrown error is a second layer. It covers values that bypass the type system, such as JSON parsed from a network response that carries a kind you have never seen.
Why the runtime check still matters
Types are erased when TypeScript compiles to JavaScript. The never check proves that your code handles every variant that the types allow. It cannot prove that the data actually matches the types.
Consider this call:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
const fromServer = JSON.parse('{"kind":"hexagon","sides":6}') as Shape;The as Shape assertion tells the compiler to trust you. At runtime fromServer.kind is "hexagon", and area(fromServer) reaches the default branch. With the plain assignment version, that branch returns undefined cast through never, and the bug travels on silently. With assertNever, it throws at the point of failure with the offending value in the message. For data from outside your program, validate it first with a type guard, as covered in the chapters on user-defined guards and on narrowing unknown.
Exhaustiveness without a default branch
You can also get exhaustiveness from the return type alone. If a function declares a return type of number and some path through a switch falls off the end, the compiler reports an error under strict settings.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function diameterOrSide(shape: Shape): number {
switch (shape.kind) {
case "circle":
return shape.radius * 2;
case "square":
return shape.size;
}
}This compiles because the compiler sees that every case returns. Add a third variant and the error is Function lacks ending return statement and return type does not include 'undefined' (error 2366). This works, but it has two weaknesses:
- It only protects functions that return a value. A
switchthat performs side effects, such as logging, has nothing to omit, so no error appears. - The error message says nothing about the missing variant, so it takes longer to diagnose.
The explicit never check protects both kinds of function and names the missing member in the message. Many teams use it everywhere for that reason.
Exhaustiveness with if chains and lookups
A switch is not required. Any construct that narrows works, because the rule is the same: after every member is ruled out, the variable is never.
type Result =
| { status: "ok"; value: number }
| { status: "error"; message: string };
function describe(result: Result): string {
if (result.status === "ok") {
return `Value: ${result.value}`;
} else if (result.status === "error") {
return `Failed: ${result.message}`;
}
const unreachable: never = result;
return unreachable;
}For mapping each variant to a constant, a Record type gives exhaustiveness through a different mechanism. A Record over a union of keys must have every key present.
type Status = "idle" | "loading" | "done";
const labels: Record<Status, string> = {
idle: "Waiting",
loading: "Working",
done: "Finished",
};Removing done from labels, or adding a fourth Status, is a compile error. Use this form when the output is data. Use switch with never when each variant needs different logic.
Gotchas
| Situation | What happens | What to do |
|---|---|---|
| A variant is added to the union | The `never` assignment fails in every function that lacks a case | Add the case in each place the compiler lists |
| A `case` is written with a typo such as `"squre"` | The compiler reports that the literal is not comparable to the union, and `square` stays unhandled | Fix the literal and rely on both errors |
| The discriminant is typed `string`, not a literal union | Narrowing never reaches `never`, so the check cannot help | Declare the property with literal types |
| A broad fallback case such as `default: return 0` is used | New variants are absorbed silently | Replace it with the `never` check |
| Data arrives from outside the program | An unknown variant reaches `default` at runtime | Use `assertNever` so it throws, and validate input |
Deliberately handling several variants with one result is fine. Stack the labels, and the never check still works:
type Event =
| { type: "click"; x: number; y: number }
| { type: "keydown"; key: string }
| { type: "keyup"; key: string };
function summarize(event: Event): string {
switch (event.type) {
case "click":
return `click at ${event.x},${event.y}`;
case "keydown":
case "keyup":
return `${event.type} ${event.key}`;
default: {
const unreachable: never = event;
return unreachable;
}
}
}Inside the stacked case, event is narrowed to the union of the two key events, so event.key is available.
Practice
Exercise
A Notification type is { channel: "email"; address: string } | { channel: "sms"; number: string }. Write a function send(n: Notification): string that returns a description for each channel and uses assertNever so that adding a "push" channel later causes a compile error in send. Then explain what error you would see after adding { channel: "push"; token: string }.
Show answer
function assertNever(value: never): never { throw new Error(Unhandled: ${JSON.stringify(value)}); }
function send(n: Notification): string {
switch (n.channel) {
case "email":
return Email to ${n.address};
case "sms":
return SMS to ${n.number};
default:
return assertNever(n);
}
}
After adding the push variant, n in the default branch has the push type, so the call reports: Argument of type '{ channel: "push"; token: string; }' is not assignable to parameter of type 'never'.
Exercise
Why can as Shape on parsed JSON defeat exhaustiveness checking, and which part of the assertNever pattern still helps?
Show answer
The assertion tells the compiler the data matches Shape without checking it, so an unknown kind passes the type system. The never check only covers variants the type lists. The runtime throw inside assertNever still fires when an unknown variant reaches the default branch, which reports the problem at the point of failure.