Sub topic 9
Narrowing and Exhaustive Checks with never
This chapter assumes you can write TypeScript functions with type annotations, that you know unions of literal types such as "up" | "down", and that you have seen enums and discriminated object shapes. Compile everything with strict turned on. Several results below depend on it.
By the end you will be able to follow how TypeScript shrinks a union inside a branch. You will also be able to make the compiler flag every switch that forgets a case when a new variant appears.
Narrowing: the type changes as the code branches
A variable has a declared type, but TypeScript also tracks a narrower type at each point in the code. The compiler reads checks such as ===, typeof, in, instanceof and switch as evidence about the value. This is called narrowing.
type Direction = "up" | "down" | "left" | "right";
function describe(d: Direction): string {
if (d === "up" || d === "down") {
// here d is "up" | "down"
return "vertical";
}
// here d is "left" | "right"
return `horizontal (${d})`;
}After the if returns, the compiler removes "up" and "down" from the union. The code after it sees only what is left. Each branch you add or return from takes more members out of the remaining set.
Common narrowing forms:
| Check | Narrows by | Example | Column |
|---|---|---|---|
| `x === "a"` | Equality with a literal | `d === "up"` | |
| `typeof x === "string"` | Primitive type | `string \ | number` |
| `Array.isArray(x)` | Array versus non-array | `string \ | string[]` |
| `"radius" in x` | Presence of a property | Object unions | |
| `x.kind === "circle"` | A shared literal field | Discriminated unions | |
| `switch (x.kind)` | The same, one case at a time | Discriminated unions |
A short example with typeof and Array.isArray:
type Input = string | string[] | number;
function normalize(input: Input): string[] {
if (typeof input === "string") {
return [input];
}
if (Array.isArray(input)) {
return input; // string[]
}
return [String(input)]; // number
}Discriminated unions
A discriminated union is a union of object types that all share one property, the discriminant. Each member gives that property a different literal type. Checking the discriminant narrows the whole object.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function describeShape(shape: Shape): string {
if (shape.kind === "circle") {
return `circle with radius ${shape.radius}`;
}
return `square with side ${shape.size}`;
}Inside the if, shape is the circle member, so shape.radius is legal. After it, shape must be the square member, so shape.size is legal. Without the discriminant, shape.radius would be an error because not every member has that property.
The discriminant can be any literal type: a string, a number, a boolean, or an enum member. Enum members work well here because each member of an enum is its own subtype.
The never type
never is the type with no values. No value can be assigned to it, so a variable of type never marks code that cannot run, or a set of possibilities that has been fully removed.
const impossible: never = "anything";
// Error: Type 'string' is not assignable to type 'never'.You normally never write that line. The useful case is a value that TypeScript has narrowed to never because every union member was eliminated. At that point, assigning it to a never variable compiles. If even one member remains, the assignment fails.
This gives you a compile-time check that a switch handles every member.
The exhaustive switch
The basic pattern puts the leftover value into a never variable in the default branch:
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 a third variant to the union:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "triangle"; base: number; height: number };The area function is unchanged, but it no longer compiles. In the default branch shape is now the triangle member, and the assignment fails with an error like Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'. The error points at the function that needs a new case, and it appears before any test runs.
A reusable assertNever helper
Writing the never variable each time is noisy. A helper function does the same job and also protects you at runtime:
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 "triangle":
return shape.base + shape.height; // simplified for the example
default:
return assertNever(shape);
}
}The parameter type never makes the call a compile error if shape still has members. The throw covers a case the compiler cannot see. Data from JSON.parse, a network response, or a cast can hold a kind the type does not allow. Without the throw, the function would quietly return undefined.
Exhaustive switches over enums
Enums work the same way, because each enum member is a distinct literal subtype:
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Banned = "BANNED",
}
function label(status: Status): string {
switch (status) {
case Status.Active:
return "On";
case Status.Inactive:
return "Off";
case Status.Banned:
return "Blocked";
default:
return assertNever(status);
}
}Add Pending = "PENDING" to Status and label stops compiling. The same check works on a plain union of string literals. Only the way you write the case labels differs.
Where exhaustiveness breaks down
These are the situations that most often make the check pass when it should not, or fail when it should not.
The discriminant was widened
If an object literal is stored in a variable without an annotation, its kind field is widened to string. Chapter material on let and as const applies here directly.
const s = { kind: "circle", radius: 2 };
area(s);
// Error: Type 'string' is not assignable to type '"circle" | "square"'.Fix it by annotating the variable (const s: Shape = ...), by using as const, or by building the value where a Shape is expected so that the context supplies the type.
A cast hides the problem
const data = JSON.parse(text) as Shape;The as Shape tells the compiler to trust you. A kind of "hexagon" passes the compile and reaches assertNever at runtime, where the throw is the only protection. For input you do not control, validate it first, with a hand-written check or a validation library, and then narrow.
Non-literal discriminants do not narrow
If the discriminant has type string or number, the compiler cannot remove members. Each case then gives it no information. Make sure the shared field is typed with literals in every member of the union.
Falsy checks on numeric enums
A numeric enum starts at 0 by default. if (level) is false for the first member, so it does not mean "a level was provided". Compare explicitly with level !== undefined, or with the member itself.
Overlapping or extra members
If a case lists a value that is not in the union, TypeScript reports an error such as Type '"hexagon"' is not comparable to type '"circle" | "square"'. That is helpful when a member is renamed, because stale cases become errors too.
Combining several members in one case
You can let cases fall through to share a result. All members listed narrow together:
type Direction = "up" | "down" | "left" | "right";
function axis(d: Direction): "vertical" | "horizontal" {
switch (d) {
case "up":
case "down":
return "vertical";
case "left":
case "right":
return "horizontal";
default:
return assertNever(d);
}
}Inside the first group, d is "up" | "down". If you forget "right", d is "right" in the default branch and the call to assertNever fails to compile.
Exhaustiveness without a switch
A lookup object can enforce the same rule. A Record over a union requires one key per member, so a missing key is an error:
type Direction = "up" | "down" | "left" | "right";
const arrows: Record<Direction, string> = {
up: "↑",
down: "↓",
left: "←",
right: "→",
};Remove right and the declaration fails. Add "diagonal" to the union and it fails again until you add a value. This suits mappings from a member to data. A switch suits mappings from a member to behavior.
Linting as a second layer
The switch-exhaustiveness-check rule in typescript-eslint reports a switch over a union or enum that lacks a case. You can use it instead of a default branch, or alongside it. It does not replace assertNever for untrusted data, because a lint rule never runs on your production input.
Summary of the pattern
- Give every member of the union a shared literal field, or use a plain literal union or enum.
- Handle each member in a
case. - End the
switchwithdefault: return assertNever(value). - Keep untrusted input from reaching the switch with an unchecked cast. Validate it first.
Exercise
This function compiles today. You then add "pending" to the Job union. What happens, and what single line in the function made that happen?
type Job = "queued" | "running" | "done";
function icon(job: Job): string {
switch (job) {
case "queued":
return "…";
case "running":
return "▶";
case "done":
return "✔";
default:
return assertNever(job);
}
}
Show answer
The function stops compiling. In the default branch job is now "pending" instead of never, so passing it to assertNever(value: never) is a type error. The line responsible is return assertNever(job);, which gives the compiler a place to check that nothing is left over. The fix is to add a case "pending": that returns an icon. At runtime, if an unexpected string still reached the function, assertNever would throw an error instead of returning undefined.
Exercise
You write const task = { kind: "start", id: 1 }; and pass task to a function that takes { kind: "start"; id: number } | { kind: "stop"; id: number }. The compiler rejects the call. Why, and give two ways to fix it.
Show answer
The variable is declared with const, but the object's properties are mutable, so kind is widened to string. string is not assignable to "start" | "stop". Two fixes: annotate the variable with the union type (const task: Action = { kind: "start", id: 1 };), or add as const to the literal so kind keeps the type "start" (and the properties become readonly).