Sub topic 2
How Control Flow Analysis Narrows Types
Assume you know basic TypeScript syntax, functions, type aliases, and union types such as string | number. You should also know JavaScript if, switch, and ternary expressions.
A union type says that a value can have one of several types. Before using that value, TypeScript must know which member of the union is currently possible. Control flow analysis is the compiler's process for tracking checks, branches, returns, and assignments so it can narrow a value to a more specific type.
Narrowing inside branches
A type guard is a condition that gives TypeScript information about a value. When the condition is true, TypeScript narrows the value in that branch.
function format(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(2);
}At the function boundary, value has type string | number. Inside the if block, the typeof check proves that value is a string. The return statement ends that path. Therefore, after the if block, the only remaining possibility is number.
The compiler follows the paths that can reach each line:
flowchart TD
A["value: string | number"] --> B{"typeof value === string?"}
B -->|yes| C["value: string"]
C --> D["return uppercase string"]
B -->|no| E["value: number"]
E --> F["return formatted number"]caption: Control flow removes impossible union members alt: A flowchart showing a string-or-number value split by a typeof check into string and number paths
Reachability changes the type
TypeScript uses reachability when it narrows types. A branch that returns, throws, or otherwise cannot continue removes that possibility from later code.
function describe(value: string | null): string {
if (value === null) {
return "No value";
}
// The null case returned, so value is string here.
return `Value: ${value.toUpperCase()}`;
}The early return is more than a runtime action. It tells the compiler that any execution reaching the final line came from the non-null path.
The same idea works with thrown errors:
function requireId(id: string | undefined): string {
if (id === undefined) {
throw new Error("An ID is required");
}
return id.toUpperCase();
}After the throw, id cannot be undefined on the remaining path.
Assignments can change a narrowed type
TypeScript also tracks assignments to variables. A variable can receive a different member of its declared union over time.
let result: string | number = "pending";
if (typeof result === "string") {
console.log(result.toUpperCase());
}
result = 200;
console.log(result.toFixed(2));The declared type remains string | number, so later assignments must fit that union. However, after assigning 200, control flow knows that the current value is a number.
This tracking applies to local variables more reliably than to changing object properties. If another part of the program can mutate a property, TypeScript may stop relying on an earlier check.
Combining conditions
TypeScript combines facts from related conditions. In this example, both checks must pass before the call is allowed:
function printName(name: string | null | undefined): void {
if (name !== null && name !== undefined) {
console.log(name.toUpperCase());
}
}The && operator means the second condition is evaluated only when the first is true. Inside the block, both null and undefined have been removed, leaving string.
When control flow becomes complicated, use small branches and early returns. This makes the runtime behavior clearer and gives the compiler simpler paths to analyze.
Exercise
What is the type of value at the final return statement? function size(value: string | number | null): number { if (value === null) { return 0; } if (typeof value === "string") { return value.length; } return value; }
Show answer
value is number. The null path returns first, and the string path returns next, so only number can reach the final statement.