Sub topic 10
Narrowing Unions with Control Flow
This chapter assumes you know union types (string | number), basic if and switch statements, and how strict mode enables strictNullChecks. A union type means a value can be one of several types. Narrowing is the compiler's process of shrinking that set based on checks in your code.
How narrowing works
When a union value could be several types, you cannot call methods that only some members support. TypeScript fixes this by tracking your checks. After an if test, the compiler knows which types remain in each branch.
function format(value: string | number | null): string {
if (value === null) {
return "none";
}
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}After the null check returns, value cannot be null. After the typeof check returns, value must be a number, so toFixed is safe.
Narrowing tools
Several checks narrow a union:
typeof x === "string"for primitives.x === nullorx === undefinedfor missing values.x instanceof Datefor class instances."radius" in xfor object shapes.- Truthiness checks like
if (x), which also remove0and"".
Truthiness checks are convenient, but they remove falsy values you may want to keep. Prefer explicit comparisons when 0 or "" are valid inputs.
Discriminated unions
A discriminated union gives each member a shared literal property, called the tag. Checking the tag narrows the whole object.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.side ** 2;
}
}Inside each case, the compiler knows which fields exist. Accessing shape.radius inside the square branch is an error.
> Note that the switch above has no default branch. Adding a new member such as "triangle" makes the function fail to compile, because the return type is number and the switch no longer covers every case.
Common errors
- Narrowing lost in callbacks. Narrowing does not carry into a function defined inside the branch when the variable is reassigned later. Copy the value into a
constfirst. - Checking the wrong property. Comparing a tag that does not exist in every member narrows nothing useful.
- Using
asto silence errors. A type assertion skips the check entirely. Narrowing with a real test is safer.
Exercise
Exercise
Given type Id = string | number, write a function that returns the id doubled when it is a number and the string repeated twice when it is a string. Which check do you use?
Show answer
Use typeof. Write: function double(id: Id): string | number { return typeof id === "number" ? id * 2 : id + id; }. The typeof check narrows id to number in the true branch and to string in the false branch.