Sub topic 6
Exhaustiveness Checking with `never`
Assume you know basic TypeScript unions, object types, functions, and discriminated unions. This chapter focuses on proving that code handles every member of a union.
A discriminated union has several object types that share a property with different literal values. For example:
type Payment =
| { kind: "card"; last4: string }
| { kind: "cash"; amount: number }
| { kind: "transfer"; account: string };The kind property is the discriminant. Its value tells TypeScript which union member a value represents.
Why exhaustive handling matters
An exhaustive function handles every possible member of a union. If a new member is added later, TypeScript should identify every function that needs updating.
Consider this function:
function describePayment(payment: Payment): string {
switch (payment.kind) {
case "card":
return `Card ending in ${payment.last4}`;
case "cash":
return `Cash payment of ${payment.amount}`;
case "transfer":
return `Transfer to ${payment.account}`;
}
}This function currently handles every Payment member. However, the compiler might not clearly report the missing case if someone later adds "crypto" to Payment. An explicit never check makes the requirement visible and enforceable.
The role of `never`
never is the type of a value that cannot exist. A function that always throws can return never because it never successfully returns:
function fail(message: string): never {
throw new Error(message);
}After TypeScript narrows all known cases from a union, the remaining value should have type never if the switch is exhaustive.
A common helper makes this check explicit:
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${String(value)}`);
}Use it in the default branch:
type Payment =
| { kind: "card"; last4: string }
| { kind: "cash"; amount: number }
| { kind: "transfer"; account: string };
function assertNever(value: never): never {
throw new Error(`Unexpected payment: ${String(value)}`);
}
function describePayment(payment: Payment): string {
switch (payment.kind) {
case "card":
return `Card ending in ${payment.last4}`;
case "cash":
return `Cash payment of ${payment.amount}`;
case "transfer":
return `Transfer to ${payment.account}`;
default:
return assertNever(payment);
}
}Inside the default branch, payment has type never. Therefore, the call is valid only when every Payment member was handled.
If you add another member:
type Payment =
| { kind: "card"; last4: string }
| { kind: "cash"; amount: number }
| { kind: "transfer"; account: string }
| { kind: "crypto"; wallet: string };The compiler reports an error at assertNever(payment). The remaining value is the "crypto" member, not never. The error points to the missing case.
Where the check belongs
Put the check in a branch that should be unreachable:
- The
defaultbranch of aswitch. - The final
elsebranch of anifchain. - A helper called after all known cases return.
For example:
type Result =
| { status: "ok"; value: number }
| { status: "error"; message: string };
function assertNever(value: never): never {
throw new Error(`Unexpected result: ${String(value)}`);
}
function formatResult(result: Result): string {
if (result.status === "ok") {
return `Value: ${result.value}`;
}
if (result.status === "error") {
return `Error: ${result.message}`;
}
return assertNever(result);
}The final call documents the assumption that no other status exists.
| Pattern | Compile-time protection | Runtime behavior |
|---|---|---|
| `default: return assertNever(value)` | Reports newly added union members | Throws if unexpected data arrives |
| `default: return "unknown"` | Does not require every member to be handled | Returns a fallback string |
| No final branch | Depends on return-type analysis and compiler settings | May return `undefined` |
Compile-time checks do not validate external data
Exhaustiveness checks protect code after TypeScript has accepted a value as a union. They do not validate JSON, user input, or API responses at runtime. External data can contain an unexpected discriminator, so the runtime behavior of assertNever still matters.
Use a useful error message, log enough context for debugging, and validate untrusted data before treating it as a trusted union.
Exercise
After adding { kind: "crypto"; wallet: string } to Payment, what does an error at assertNever(payment) mean?
Show answer
The switch does not handle the new union member, so the narrowed value is not never. Add a "crypto" case before the final check.