Chapter 3: Narrowing and Control Flow Analysis
Runnable examples: examples/ch03-narrowing.ts
A variable has a declared type, but at each point in your code TypeScript tracks a possibly smaller narrowed type, based on the checks that came before. This is control flow analysis.
The built-in narrowing checks
function describe(value: string | number | boolean | null | Date | string[]) {
if (value === null) return "null"; // equality
if (typeof value === "string") return value.length; // typeof
if (typeof value === "number") return value.toFixed(1);
if (typeof value === "boolean") return value ? "yes" : "no";
if (value instanceof Date) return value.toISOString(); // instanceof
return value.length; // only string[] is left
}
| Check | Narrows by |
|---|---|
typeof x === "string" |
primitive kind ("string", "number", "bigint", "boolean", "symbol", "undefined", "object", "function") |
x === null, x === "a" |
equality with a literal |
if (x) |
truthiness (removes null, undefined, and falsy literals) |
"key" in x |
presence of a property |
x instanceof C |
prototype chain |
Array.isArray(x) |
array-ness |
x.kind === "circle" |
discriminant property (see below) |
custom x is T function |
your own logic |
Watch out: typeof null === "object", and truthiness narrowing removes 0 and "" too, which is often a bug when they are valid values.
Discriminated unions: the most useful pattern in TypeScript
Give each variant a literal-typed tag property:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number }
| { kind: "triangle"; base: number; height: number };
Checking the tag narrows the whole object:
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2; // shape is the circle variant
case "rect": return shape.width * shape.height;
case "triangle": return (shape.base * shape.height) / 2;
default: return assertNever(shape);
}
Exhaustiveness checking with never
In the default branch, every variant has been handled, so shape is never. assertNever(value: never) only accepts never. If someone adds { kind: "hexagon" } to Shape, the default branch now receives a hexagon, and the call stops compiling, pointing at every switch you need to update. This turns “forgot a case” from a runtime bug into a compile error.
Type predicates: teach TypeScript your own checks
function isDefined<T>(value: T | null | undefined): value is T {
return value !== null && value !== undefined;
}
[1, null, 2].filter(isDefined); // number[]
A predicate is a promise: if your function returns true, the value is of that type. TypeScript does not verify the body, so a wrong predicate silently lies.
Since TypeScript 5.5, simple arrow functions like (w) => w !== undefined get an inferred type predicate, so filter narrows without a helper in many cases.
Assertion functions
function assertIsString(value: unknown, name = "value"): asserts value is string {
if (typeof value !== "string") throw new TypeError(`${name} must be a string`);
}
function shout(input: unknown) {
assertIsString(input);
return input.toUpperCase(); // input is string from here on
}
Use them at boundaries (parsing input, checking invariants) to narrow for the rest of a function without nesting.
When narrowing is forgotten
Narrowing applies to a specific reference at a specific point. It can be lost:
- Inside callbacks, for mutable variables and properties: the callback may run later, after the value changed. Copy into a
constfirst:
if (state.user) {
const user = state.user; // narrowed copy
return schedule(() => user.name); // safe inside the callback
}
-
After function calls, TypeScript generally keeps narrowing of properties even though a call could mutate them. This is a deliberate trade-off for usability, and a place where the type system is optimistic.
-
Across aliases of conditions it works since TypeScript 4.4:
const isString = typeof x === "string"; if (isString) { x.toUpperCase() }.
Check yourself
- Why is
if (count)a risky narrowing forcount: number | undefined? - What happens to an exhaustive
switchwithassertNeverwhen a new variant is added? - What does TypeScript check inside the body of a type predicate function?
Answers
1. It also removes `0`, which is usually a valid count. Use `count !== undefined`. 2. The default branch no longer receives `never`, so the `assertNever` call fails to compile. 3. Only that it returns a boolean. The predicate's correctness is your responsibility.Next: Chapter 4, Generics