Skip to content

Narrowing: how TypeScript follows your ifs

Working knowledgeConcept

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:

format.ts
function format(value: string | number) {
return value.toFixed(2);
}
Shell
$ tsc --strict --noEmit format.ts
format.ts(2,16): error TS2339: Property 'toFixed' does not exist on type 'string | number'.
Property 'toFixed' does not exist on type 'string'.

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.

label.ts
function label(value: string | number | undefined): string {
if (value === undefined) {
return '-';
}
if (typeof value === 'string') {
return value.trim();
}
return value.toFixed(2);
}
The checker walks label()
Step 1 of 7
Type of value string | number | undefined
What value can be here
string
number
undefined
Type at each use
Empty
  • 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.

1 line

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:

Conditions that narrow, and what they keep in the true branch
ConditionKeepsTypical use
typeof x === 'string'members with that typeof resultprimitives: string, number, boolean, function
x === undefined, x !== nullmembers equal (or not) to that valueoptional values
if (x)members that can be truthydrop null and undefined
'swim' in petmembers that have, or may have, swimobject unions without a tag
x instanceof Datemembers that are Date (or subclasses)class instances
Array.isArray(x)array membersstring | string[] inputs
s.kind === 'circle'members whose kind is that literaldiscriminated unions
isFish(pet)what the predicate declaresyour 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.

Optional fields
type Req = {
status: 'loading' | 'ok' | 'error';
data?: string;
error?: Error;
};
if (r.status === 'ok') {
r.data; // string | undefined
}
Discriminated union
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.

area.ts
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number }
| { kind: 'triangle'; base: number; height: number };
function area(s: Shape): number {
switch (s.kind) {
case 'circle':
return Math.PI * s.radius ** 2;
case 'square':
return s.side ** 2;
default: {
const unhandled: never = s;
throw new Error(`Unknown shape: ${unhandled}`);
}
}
Shell
$ tsc --strict --noEmit area.ts
area.ts(13,13): error TS2322: Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'.

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.

TypeScript
type Fish = { swim(): void };
type Bird = { fly(): void };
function isFish(pet: Fish | Bird): pet is Fish {
return 'swim' in pet;
}
if (isFish(pet)) pet.swim();
else pet.fly();

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.

08 Check yourself

Question

function f(v: string | null) { if (typeof v === 'object') { … } } What is v's type inside the if?

Question

You add { kind: 'hexagon' } to Shape, and area ends with const unhandled: never = s;. What happens?

Question

Inside if (r.status === 'ok') on a discriminated union, why can you read r.data without a check?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?