Sub topic 10
Narrowing unions with control flow
This chapter assumes you know the primitive types, union types, literal types, and how null and undefined behave under strictNullChecks. Turn on strict in your tsconfig.json before you try the examples.
What narrowing is
A union type such as string | number | null says a value could be any one of several types. You can only use operations that are valid for every member. Narrowing is the compiler's process of shrinking a union to fewer members at a given point in the code, based on checks you wrote.
TypeScript does this by following control flow. It reads if, switch, return, throw, loops, and logical operators, and tracks what must be true at each line. Inside a branch, the variable has a narrower type than its declared type. This is called control flow analysis.
function describe(value: string | number | null): string {
if (value === null) {
return "none";
}
// value: string | number here, because the null branch returned
if (typeof value === "string") {
return value.toUpperCase();
}
// value: number here
return value.toFixed(2);
}Each early return removes members from the union for the code that follows. You do not need an else.
Kinds of checks the compiler understands
The compiler only narrows on checks it recognizes. These are the common ones.
| Check | Example | What it narrows |
|---|---|---|
| `typeof` | `typeof x === "string"` | Primitives: `string`, `number`, `boolean`, `bigint`, `symbol`, `undefined`, `function`, `object` |
| Equality | `x === null`, `x === "a"` | `null`, `undefined`, and literal members |
| Truthiness | `if (x)` | Removes `null`, `undefined`, `0`, `""`, `false` |
| `in` | `"swim" in pet` | Object types by property name |
| `instanceof` | `x instanceof Date` | Class instances |
| Discriminant property | `shape.kind === "circle"` | Unions of objects that share a literal property |
| User-defined guard | `isString(x)` | Anything you describe with a type predicate |
typeof and equality
typeof returns one of a fixed set of strings, and TypeScript understands each one. Note that typeof null is "object", so a typeof x === "object" check leaves null in the type unless you also exclude it.
function size(input: string | string[] | null): number {
if (typeof input === "object") {
// input: string[] | null, because typeof null is "object"
return input === null ? 0 : input.length;
}
return input.length; // input: string
}Equality checks narrow in both directions. Comparing two values also narrows when their types overlap.
function same(a: string | number, b: string | boolean): void {
if (a === b) {
// a and b can only both be string here
console.log(a.toUpperCase(), b.toUpperCase());
}
}Truthiness and its trap
A truthiness check removes null and undefined, which is convenient. It also removes 0, "", and NaN, which are often valid values.
function printCount(count: number | undefined): void {
if (count) {
console.log(`Count: ${count}`);
} else {
// Runs for undefined AND for 0
console.log("No count");
}
}
function printCountSafe(count: number | undefined): void {
if (count !== undefined) {
console.log(`Count: ${count}`);
} else {
console.log("No count");
}
}printCount(0) prints "No count", which is almost certainly a bug. Compare against undefined or null explicitly when zero or an empty string is a legitimate value. The ?? operator follows the same principle: count ?? 0 replaces only null and undefined, while count || 0 replaces every falsy value.
The in operator
For unions of object types, in narrows by whether a property exists.
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird): void {
if ("swim" in animal) {
animal.swim(); // Fish
} else {
animal.fly(); // Bird
}
}instanceof
instanceof narrows to a class type. It works only for values created from constructors, not for plain objects or interfaces.
function format(input: Date | string): string {
if (input instanceof Date) {
return input.toISOString();
}
return input;
}Discriminated unions
When each member of a union has a property with a distinct literal type, you can narrow by checking that property. The shared property is called the discriminant.
type Result =
| { status: "ok"; value: number }
| { status: "error"; message: string };
function show(result: Result): string {
if (result.status === "ok") {
return `Value: ${result.value}`;
}
return `Error: ${result.message}`;
}This pattern is usually clearer than a set of optional properties, because the compiler ties each property to the one state where it exists. A switch on the discriminant works the same way and can be made exhaustive. Chapter coverage of never explains how to make the compiler report a missing case.
User-defined type guards
When the built-in checks are not enough, write a function whose return type is a type predicate, in the form param is Type. If the function returns true, the compiler narrows the argument in the calling code.
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((item) => typeof item === "string");
}
function join(input: unknown): string {
if (isStringArray(input)) {
return input.join(", "); // input: string[]
}
return "";
}The compiler trusts your predicate. It does not verify that the body actually matches the claim. A guard that returns true for the wrong inputs gives you wrong types with no error.
Where narrowing stops working
Narrowing is local and conservative. These cases catch intermediate developers most often.
- Reassignment resets it. Assigning to a variable narrows it to the assigned type, but a
letcaptured in a callback loses its narrowing, because the callback may run after the value changes. - Property access is narrowed only while stable.
if (user.name !== undefined)narrowsuser.nameuntil something the compiler cannot see might change it, such as a function call in between. In practice the compiler keeps the narrowing across calls for property paths, so do not rely on it when other code mutates the object. - Callbacks. A narrowing from outside a function does not always carry into it for mutable variables.
function run(value: string | undefined): void {
let current = value;
if (current !== undefined) {
current.toUpperCase(); // ok: string
[1, 2].forEach(() => {
// current.toUpperCase(); // Error in older versions: 'current' is possibly 'undefined'
});
}
}The reliable fix is to copy the narrowed value into a const, which cannot be reassigned, and use that.
function runSafe(value: string | undefined): void {
if (value === undefined) {
return;
}
const text = value; // const: type is string
[1, 2].forEach(() => {
console.log(text.toUpperCase());
});
}Recent TypeScript releases keep narrowing inside closures when the variable is a const or a parameter that is never reassigned. Copying to a const works on every version.
Common mistakes
- Using truthiness on numbers and strings. It treats
0and""as missing. Compare withundefinedornullinstead. - Forgetting that
typeof nullis"object". Add an explicitnullcheck. - Reaching for
asinstead of a check. An assertion silences the compiler, while a check proves the type at run time. - Writing a guard that does not match its predicate. The compiler cannot catch this.
- Expecting
into narrow a class with optional properties. If both union members could have the property,incannot separate them.
Summary of the working model
Declare a union to describe every case. Write checks the compiler recognizes. Let each branch see a smaller type. If you find yourself needing an assertion, first ask whether a discriminant property, an in check, or a type guard would express the same fact in a way the compiler can verify.
Exercise
The function below compiles, but format(0) returns "missing". Explain why, and rewrite the function so that format(0) returns "0" and format(undefined) returns "missing".
function format(n: number | undefined): string {
if (n) {
return String(n);
}
return "missing";
}
Show answer
The check if (n) is a truthiness test. It removes undefined, but it also treats 0 as false, so the zero case falls through to "missing". Compare against undefined explicitly:
function format(n: number | undefined): string {
if (n !== undefined) {
return String(n);
}
return "missing";
}
Exercise
Given type Event = { kind: "click"; x: number; y: number } | { kind: "key"; code: string }, write a function label(e: Event): string that returns "click at x,y" for clicks (with the actual numbers) and "key code" for key events (with the actual code), using narrowing and no type assertions.
Show answer
function label(e: Event): string {
if (e.kind === "click") {
return click at ${e.x},${e.y};
}
return key ${e.code};
}
Checking the discriminant kind narrows e to the click member inside the if, so x and y are available. After the early return, e is the key member, so code is available.