Sub topic 2
How control flow analysis narrows types
This chapter assumes you can read basic TypeScript (type aliases, functions, interfaces) and know what a union such as string | number is. It also assumes you know if, switch, and the ternary operator in JavaScript. It explains the mechanism behind all narrowing. Later chapters cover each specific check in detail.
Declared type and narrowed type
Every variable has a declared type. Inside a function, the compiler also tracks a narrowed type for each place where you read the variable. The narrowed type is the declared type, filtered by what the compiler can prove about the code that ran before that point.
function describe(id: string | number): string {
// Here, id is string | number
if (typeof id === "string") {
// Here, id is string
return id.toUpperCase();
}
// Here, id is number
return id.toFixed(0);
}The declared type of id never changes. What changes is the type the compiler assigns to each use of id. This process is called control flow analysis. Narrowing only ever moves from a wider type to a narrower one, and only within the declared type's members.
The working model: a graph of paths
The compiler builds a control flow graph for each function. The graph has these parts:
- Nodes are statements and expressions.
- Edges are the ways execution can move from one node to the next.
- Conditions such as
if,&&,||,?:,switch, and loop tests split an edge into a true edge and a false edge.
A narrowing check attaches a filter to each of those edges. For a read of id, the compiler walks backward along every path that can reach that read. It applies the filters it meets, then combines the results from all paths with a union.
This gives three rules:
- On a branch, apply the condition's filter (or its opposite on the false edge).
- At a join point where paths merge, take the union of the types arriving on each path.
- On a path that ends in
return,throw,break, orcontinue, nothing flows onward. That path contributes nothing to later code.
The code behind that diagram:
function pad(input: string | number | null): string {
if (input === null) {
input = "";
}
// The true path ends with input: string.
// The false path arrives with input: string | number.
// The join gives string | number.
return String(input).padStart(5, "0");
}The null member is gone after the join, because neither path can still hold it.
Early exits
Rule 3 is the reason guard clauses work. When a branch cannot continue, only the other branch reaches the code after it.
function lengthOf(value: string | undefined): number {
if (value === undefined) {
throw new Error("value is required");
}
// Only the path where value !== undefined reaches here.
return value.length;
}The same holds for return, and for continue or break inside loops. A function that returns never, such as one whose body always throws, also ends a path, as long as the compiler can see its declared return type. For this to work, the function must be declared with an explicit never return annotation, such as a function-declaration or a const with a type annotation.
Conditions that narrow
The compiler understands several forms of condition. This chapter only lists the forms. The next chapters cover them one by one.
| Form | Example | Narrows |
|---|---|---|
| `typeof` check | `typeof x === "string"` | primitives |
| Truthiness | `if (x)` | removes falsy members |
| Equality | `x === null`, `x === "a"` | literals, `null`, `undefined` |
| `in` | `"swim" in x` | object unions |
| `instanceof` | `x instanceof Date` | class instances |
| User-defined guards | `isUser(x)` | whatever the predicate states |
Conditions combine as you would expect. In a && b, the filter from a is already applied when b is evaluated. In a || b, the opposite filter from a applies when b is evaluated. The ternary operator applies the filter to each branch.
function safeLength(s: string | undefined): number {
return s !== undefined && s.length > 0 ? s.length : 0;
}In s.length > 0, the type of s is string, because the left side of && already excluded undefined. The ternary's true branch also uses s.length, and the full condition must have been true to reach it.
Narrowing by assignment
Assignment is the other source of narrowing. When you assign to a variable whose declared type is a union, the compiler narrows it to the members that the assigned value can have.
let value: string | number = "hello";
console.log(value.toUpperCase()); // value is string here
value = 42;
console.log(value.toFixed(1)); // value is number hereTwo details matter here.
- The narrowing only works when the declared type is a union. For
let x = "a", the inferred declared type isstring, so there is nothing to narrow. - The narrowing uses the type of the assigned expression. If that expression is itself the full union, the variable stays wide.
let wide: string | number = Math.random() > 0.5 ? "a" : 1;
// The assigned expression has type "a" | 1, so wide is narrowed to string | number.
// Calling wide.toUpperCase() is still an error.Because the conditional expression yields a union, the variable keeps the union. To use a string method, you must check first.
Loops
Loops add edges that go backward. The compiler has to account for the type at the top of the loop coming either from before the loop or from the end of a previous iteration.
function firstDefined(items: (string | undefined)[]): string {
let found: string | undefined;
for (const item of items) {
if (item !== undefined) {
found = item;
break;
}
}
// Paths here: the loop ended without a match (found is undefined),
// or it left through break (found is string).
return found ?? "none";
}After the loop, found is string | undefined. That matches reality, since the loop might never find anything. Control flow analysis follows what can actually happen. It does not follow what you hope happens.
Exhausting a union
When every member of a union is excluded, the remaining type is never. This is the empty type, with no possible values.
function show(x: string | number): string {
if (typeof x === "string") {
return x;
} else if (typeof x === "number") {
return x.toString();
} else {
// x is never here
return x;
}
}A variable of type never in a branch tells you that the branch is unreachable by the types. A later chapter uses this to enforce exhaustive handling of discriminated unions. For now, remember that never is the normal result of narrowing away every option. It does not indicate a compiler bug.
What counts as a narrowable reference
Narrowing is attached to references. A reference is an expression the compiler can recognize as the same thing across two points in the code. The supported kinds are:
- A variable or parameter:
x. - A property access chain:
user.profile.name. - An element access with a literal key:
config["mode"]. this.
A function call is not a reference, because each call may return something different. Narrowing a call result has no effect on the next call.
function getValue(): string | number {
return Math.random() > 0.5 ? "a" : 1;
}
function bad(): string {
if (typeof getValue() === "string") {
// This is a second call. The checked result was not stored.
// return getValue().toUpperCase(); // error: property does not exist on string | number
}
return "";
}
function good(): string {
const v = getValue(); // store the result once
if (typeof v === "string") {
return v.toUpperCase();
}
return String(v);
}Store the value in a const first, then check the const. This is the single most common fix for "narrowing didn't work".
Optimism about function calls
The compiler does not discard narrowing of a property when you call a function. It assumes the call does not change the property. This is a deliberate trade-off. If it discarded narrowing at every call, most real code would stop compiling. The cost is that the compiler can be wrong.
type User = { name?: string };
function clearName(user: User): void {
user.name = undefined;
}
function risky(user: User): number {
if (user.name !== undefined) {
clearName(user);
return user.name.length; // compiles, then throws at run time
}
return 0;
}The compiler reports no error, yet user.name is undefined when the length is read. When a call between the check and the use could change the value, copy the value into a const before the call, as the earlier example did.
Common errors and how to read them
- "Property 'x' does not exist on type 'A | B'". The code reads a member that only one union member has. Check which narrowing form fits, or confirm the check actually covers this path.
- "Object is possibly 'undefined'". Some path to this read still includes
undefined. Look for a branch that does not return or throw. - Narrowing works at the check but not inside a callback. Callbacks run later, so the compiler is cautious about mutable variables. The final chapters of this tutorial cover this limit, along with the
constfix. - The type is
neverunexpectedly. Your checks excluded every member. This usually means a condition is contradictory, such as testingtypeof x === "string"on a value declared asnumber.
To see the narrowed type at any point, hover over the variable in your editor. This is the most direct way to see what control flow analysis has concluded. When it disagrees with your expectation, trace the paths that reach that point and find the one that still carries the wider type.
Exercise
In the function below, what is the narrowed type of input on the line marked // HERE, and why?
function f(input: string | number | null): number {
if (input === null) {
return 0;
}
if (typeof input === "string") {
input = input.length;
}
// HERE
return input;
}
Show answer
It is number. The first if returns on the null path, so only string | number continues. In the second if, the true path assigns a number (input.length), so that path ends with number. The false path has already excluded string, so it carries number. The join of number and number is number, which is why return input is valid.
Exercise
Why does if (typeof getValue() === "string") { getValue().toUpperCase(); } fail to compile, and what is the fix?
Show answer
Each call to getValue() is a separate expression, not a reference that the compiler can track, so the check on the first call does not narrow the second. Store the result in a const (const v = getValue();), then check v and use v inside the branch.