Narrowing: how TypeScript follows your ifs
TypeScript rejects value.toFixed(2), yet accepts the very same line once it sits under an if. The checker reads your conditions and works out a narrower type for each branch. Here is how it does that, which checks it understands, and how to make it tell you when you forgot a case.
01 The same line, rejected then accepted
A value that may be a string or a number cannot be formatted with toFixed, because strings have no toFixed. The compiler says so:
Put a typeof check in front and the error goes away, with no cast and no annotation. The declared type of value did not change. What changed is the type the checker uses at that line.
02 The checker follows the control flow
This is called narrowing. As the checker reads a function top to bottom, it tracks every path the code can take. A condition such as value === undefined splits the path in two, and on each side the checker removes the members of the union that cannot be there. When a branch ends in return or throw, the code after it only runs on the other side, so the narrowing carries on past the if.
- still possible
- the type on this line
- ruled out here
- just recorded
At the top of the function, value has its declared type: any of the three. Calling value.trim() here would be an error, because two of the three have no trim.
Nothing here runs at compile time. The checker is reasoning about which values could reach each line. At runtime the same if statements run as ordinary JavaScript, which is why narrowing can be trusted: the check that convinced the compiler is the very check that protects the line.
03 The checks it understands
Narrowing only works with conditions the checker recognises. These are the common ones, in TypeScript 5.x:
| Condition | Keeps | Typical use |
|---|---|---|
| typeof x === 'string' | members with that typeof result | primitives: string, number, boolean, function |
| x === undefined, x !== null | members equal (or not) to that value | optional values |
| if (x) | members that can be truthy | drop null and undefined |
| 'swim' in pet | members that have, or may have, swim | object unions without a tag |
| x instanceof Date | members that are Date (or subclasses) | class instances |
| Array.isArray(x) | array members | string | string[] inputs |
| s.kind === 'circle' | members whose kind is that literal | discriminated unions |
| isFish(pet) | what the predicate declares | your own checks |
In the false branch you get the rest: whatever the true branch could not be. A condition the checker does not recognise, such as if (getKind(x) === "a"), narrows nothing, even if you know it is right.
04 Discriminated unions: one field decides
For object types, the cleanest pattern is a shared literal field, often called kind, type or status. Checking that one field tells the checker exactly which member you have, and with it, which other fields exist.
type Req = {status: 'loading' | 'ok' | 'error';data?: string;error?: Error;};if (r.status === 'ok') {r.data; // string | undefined}
type Req =| { status: 'loading' }| { status: 'ok'; data: string }| { status: 'error'; error: Error };if (r.status === 'ok') {r.data; // string}
On the left, the type allows nonsense such as status: "loading" with data set, so checking status proves nothing about data. On the right, every valid combination is spelled out. Inside the if, r is { status: 'ok'; data: string }, and touching r.error there is an error: Property 'error' does not exist.
05 The never check: make forgetting a compile error
Narrow away every member of a union and nothing is left. TypeScript calls that empty type never, and no value can be assigned to it. That gives you a free exhaustiveness check: put the leftover into a never variable at the end.
Someone added triangle to Shape but not to area. Without the never line this compiles and returns nothing useful at runtime. With it, the error names the missing case. Add a case 'triangle' and the leftover becomes never, so the line compiles again. Both outputs here are real tsc 5.9 runs.
Keep the throw. If bad data arrives from outside (say, kind: "hexagon" from an API), the types were wrong and the default branch does run. The check catches your mistakes at compile time; the throw catches the world’s at runtime.
06 Teaching it your own checks
When the test is too complex for the built-in guards, write a function whose return type is a type predicate, x is T. A true result narrows the argument to T at the call site.
Since TypeScript 5.5 the checker can infer simple predicates on its own, which is why [1, undefined, 3].filter((x) => x !== undefined) is now typed number[] rather than (number | undefined)[].
The checker does not verify that a predicate’s body matches its claim. function isStr(x: unknown): x is string { return typeof x === "number"; } compiles without a word, and every caller then trusts a lie. Keep predicate bodies short and obvious.
07 Where narrowing lets you down
if (typeof v === 'object') {
v.name; // v may be null
}typeof null is 'object'JavaScript reports null as "object", and the checker models that faithfully, so v keeps null in this branch. Check v !== null as well, or use if (v) first.let prefix: string | undefined = …;
if (prefix !== undefined) {
names.map((n) => prefix.toUpperCase());
}
prefix = undefined;Callbacks and reassigned variablesThe callback may run later, after prefix changed, so the checker drops the narrowing inside it: 'prefix' is possibly 'undefined'. Since TypeScript 5.4 this only happens if the variable is assigned again later. Copy it into a const to fix it.if (!count) return;
// 0 was dropped tooTruthiness drops real valuesif (x) removes 0, "" and NaN along with null and undefined. Use x !== undefined or x != null when zero or the empty string are valid.if (user.role !== undefined) {
reset(user); // may clear role
user.role.length; // no error
}Narrowing a property, then calling codeNarrowing of user.role survives the call to reset, even though that call could have changed it. The checker is optimistic here; copy the property into a local const when other code might mutate the object.const x = input as Shape;Casting instead of narrowingas tells the checker to believe you; nothing checks it at runtime. A real check, a guard or a parser, narrows and protects the line at the same time.