Introduction
A union says a value is one of several types, but to do anything specific with it you need to know which. TypeScript follows your code's checks, narrowing the value's type after each one: inside if (typeof v === "string"), v is a string. This lesson lists the checks TypeScript understands, and shows how to make it prove that you handled every case.
How it works
TypeScript's control flow analysis reads each if, switch, return and assignment and works out the type of every value at every line. These checks narrow a union:
typeof v === "string","number","boolean","object"and so on.- Equality:
v === null,v !== undefined, orstatus === "paid"on a literal union. - Truthiness:
if (name)removesnull,undefinedand the empty string. v instanceof Datefor classes."last4" in pwhen only some members have that property.- A discriminant:
s.kind === "circle"on a discriminated union.
Narrowing also works "by elimination". After if (value === null) return ...; the rest of the function knows value is not null, and after the string and number cases are handled, only Date is left.
For a switch over a discriminant, an exhaustiveness check makes the compiler prove that every case is handled. In the default branch, assign the value to a variable of type never, the type with no values. If every kind was handled, nothing can reach default, so the assignment is fine. If someone later adds a "triangle" to the union, s in default has type triangle, which is not assignable to never, and the compiler points at this line.
When a check is more complex, wrap it in a user-defined type guard: a function whose return type is x is string[]. Wherever it returns true, TypeScript narrows its argument:
function isStringArray(x: unknown): x is string[] {
return Array.isArray(x) && x.every((item) => typeof item === "string");
}
TypeScript trusts a type guard's answer, so the function must really check what it promises.
Example
// Narrowing: each check tells TypeScript more about a value.
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; side: number }
| { kind: "rect"; w: number; h: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.round(Math.PI * s.r * s.r);
case "square":
return s.side * s.side;
case "rect":
return s.w * s.h;
default: {
const unreachable: never = s; // an error here if a kind were not handled
return unreachable;
}
}
}
function format(value: string | number | Date | null): string {
if (value === null) return "(empty)";
if (typeof value === "string") return value.toUpperCase();
if (typeof value === "number") return value.toFixed(2);
return value.toISOString().slice(0, 10); // only Date is left
}
function isStringArray(x: unknown): x is string[] {
return Array.isArray(x) && x.every((item) => typeof item === "string");
}
console.log(area({ kind: "circle", r: 2 }), area({ kind: "rect", w: 2, h: 5 }));
console.log(format("hi"), format(3.14159), format(null), format(new Date(Date.UTC(2024, 0, 15))));
const data: unknown = JSON.parse('["a", "b"]');
if (isStringArray(data)) console.log(data.join("+"));Line by line
areaswitches onkind; in each case, only that shape's fields are available.- The
defaultbranch assignsstonever: with every kind handled,shas type never there. formatremovesnullfirst, then string and number; whatever is left must be aDate.isStringArraychecks anunknownvalue and tells TypeScript it is astring[]when it returns true.- After the guard,
data.joinis allowed.
Expected result
13 10
HI 3.14 (empty) 2024-01-15
a+b
In the real world
Narrowing is how TypeScript code handles every API response, form value and message: check, then use. Exhaustiveness checks are common in state machines and reducers, where a new state or action type must not be forgotten anywhere. Validation libraries are built from type guards, turning a run-time check of unknown data into a static type.
Common mistakes
- Checking typeof v === "object" to rule out null: typeof null is "object" too.
- Using truthiness on numbers:
if (count)treats 0 as missing. - Writing a type guard that does not really check, which lies to the compiler.
- Losing narrowing in callbacks: a narrowed
letvariable may change before the callback runs, so TypeScript forgets the check there.
Best practices
- Handle the special cases first (
null, errors) and return early; the rest of the function is then simpler. - End every switch over a discriminated union with a
nevercheck. - Prefer
===comparisons and discriminants to truthiness when 0 or "" are valid values.
Summary
Checks narrow unions: typeof, equality, truthiness, instanceof, in and discriminants each tell TypeScript more about a value, inside a branch and after an early return. A never assignment in default makes the compiler prove a switch is exhaustive, and functions returning x is T turn your own checks into type guards.
Quick check
Key takeaways
- A check on a union value narrows it in the branch where the check is true, and in the rest of the code after a return.
- Switch on a discriminant and end with a never assignment to have TypeScript prove that every case is handled.
- Write x is T functions to name checks you repeat.
Practice problems for this lesson
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.