Control flow analysis and narrowing
How the checker follows if, return, and assignment to give a variable a narrower type on each line, using truthiness and equality checks.
Union and literal typesNull, undefined, and strict null checks
Control flow analysis and narrowing
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A variable has a declared type, fixed where it is declared, and a narrowed type, which the checker works out separately for each point in the code from the checks and assignments that came before.
- Control flow analysis reads `if`, `else`, early `return`, `throw`, `&&`, `||`, and ternaries, and removes from a union every member that a branch has ruled out.
- A truthiness check removes `null` and `undefined`, but it also throws away `0`, `""`, and `NaN`, so `if (count)` is the wrong test for a number that can legitimately be zero.
- Comparing with `===` narrows both sides to the types they could share, and `x != null` is the one loose comparison worth using, because it rules out `null` and `undefined` together.
- Assigning to a variable narrows it to the assigned value's type, but only within its declared type; you can't assign something the declaration doesn't allow.
- Narrowing doesn't survive everywhere: inside a callback, a `let` variable that is reassigned later goes back to its declared type, because the checker can't know when the callback will run.
A union you can’t use yet
Union types let you say a value is one of several things: number | null, string | undefined, "draft" | "published". The catch is what you can do with such a value. On a number | null, you can only use operations valid for both members, which means almost nothing. price.toFixed(2) is an error, because null has no toFixed.
At runtime you would just check first. The reason TypeScript is pleasant to use is that it watches you check:
function formatPrice(price: number | null): string {
if (price === null) {
return "Free";
}
return `$${price.toFixed(2)}`; // price: number
}
No cast, no extra annotation. After the if returns early, the checker knows null is gone, so price is a number for the rest of the function. This is narrowing, and the machinery behind it is called control flow analysis.
Declared type vs narrowed type
Think of it this way. Every variable has a declared type, the one written on its declaration or inferred there. That never changes. On top of it, the checker keeps a narrowed type for each point in the code, the declared type minus whatever earlier code has ruled out.
The checker gets there by walking the paths your code can take: into an if or its else, past a return or throw, through the right-hand side of && or ||, into either arm of a ternary. On each path it asks what must be true to have arrived here, and trims the union to match. Hover over the same variable on two different lines in your editor and you can watch the type change.
Assignment narrows too:
let input: string | number = "42";
input.toUpperCase(); // input: string
input = 7;
input.toFixed(1); // input: number
The declared type string | number still governs what you may assign. Narrowing only ever picks out a part of the declared type; it never widens past it.
Truthiness narrowing
The most common check is plain truthiness: if (user), name && name.trim(), !error. In a truthy branch, the checker removes null and undefined (and false, if it was in the union).
The trap is what else JavaScript counts as falsy: 0, "", and NaN. Those are real values of number and string, so a truthiness test quietly sorts them in with “missing”:
function describe(count: number | undefined) {
if (count) {
return `${count} items`; // count: number
}
return "No count"; // count: number | undefined, and 0 lands here
}
TypeScript is honest about it. In the falsy branch, count is still number | undefined, because a falsy number could be 0. If zero is a valid count, test what you mean: count !== undefined.
Equality narrowing
=== and !== against a specific value narrow to match. Comparing to null or undefined is the everyday case, and comparing to a literal like status === "draft" narrows a union of string literals the same way.
Comparing two variables narrows both. If a is string | number and b is string | boolean, then inside if (a === b) both are string, since that’s the only type they could share and still be equal.
Loose equality earns one exception. == null is true for exactly null and undefined, so it is a compact way to rule out both at once:
function shout(v: string | null | undefined) {
if (v != null) {
return v.toUpperCase(); // v: string
}
}
Where narrowing stops
Narrowing is tied to a point in the control flow, and a callback runs at some other point. For a const or a parameter that is never reassigned, TypeScript carries the narrowing into the callback. For a let that is reassigned later in the function, it can’t, because the callback might run after that reassignment:
declare function getLabel(): string | undefined;
let label: string | undefined = getLabel();
if (label !== undefined) {
setTimeout(() => label.toUpperCase(), 0);
// error: 'label' is possibly 'undefined'.
}
label = undefined;
The fix is usually to copy the narrowed value into a const before creating the callback. When the checker refuses a narrowing you expected, ask whether some other code could change the value between the check and the use. It usually could.
About the video
The embed starts at the video’s “Control Flow Analysis” chapter (3:41). Nicos Tsourektsidis traces how the checker reads code line by line, then covers falsy and truthy values, the ternary, logical operators, comparison operators, and coercion, which is this lesson’s ground. He also covers typeof and instanceof around the 7:41 mark, which the next lesson uses as its embed. Exhaustiveness and type predicates near the end each get their own lesson later in this group.
Check yourself
In `function f(price: number | null)`, after `if (price === null) return;`, what is the type of `price` on the next line, and why?
It is `number`. The early return means the rest of the function only runs when `price` is not `null`, so control flow analysis removes `null` from the union for every line after the check.
Why is `if (count) { ... }` a poor way to check that a `number | undefined` parameter was provided?
A truthiness check treats `0` as falsy, so a real count of zero lands in the same branch as `undefined`. The checker can't narrow the falsy branch to just `undefined` either, because it still could be `0`. Use `count !== undefined` instead.
What does `if (value != null)` narrow `string | null | undefined` to, and why is the loose `!=` acceptable here?
It narrows to `string`. Loose equality treats `null` and `undefined` as equal to each other and to nothing else, so `!= null` excludes exactly those two values in one test, and TypeScript models that precisely.
Given `let input: string | number = "42";`, why does `input.toUpperCase()` compile on the next line, and what happens after `input = 7;`?
The assignment narrows `input` to `string`, so string methods are allowed. After `input = 7` it is narrowed to `number`, so `input.toFixed(1)` compiles and `toUpperCase` would not. The declared type `string | number` still limits what can be assigned.
Why might a value you checked with `if (label !== undefined)` be typed as possibly undefined again inside a `setTimeout` callback?
If `label` is a `let` that gets reassigned somewhere after the callback is created, the checker can't tell whether that reassignment happens before the callback runs, so it falls back to the declared type inside the callback. A `const` or a parameter that is never reassigned keeps its narrowing.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.