Control Flow Analysis in TypeScript
How TypeScript tracks a variable's type through ifs, loops, assignments and returns, what narrows it, and the cases where narrowing is lost, with exact errors.

A variable in TypeScript does not have one fixed type everywhere it appears. A parameter declared as string | number can be a string inside one branch and a number after another, and the compiler knows which, without any annotation from you. The machinery that does this is control flow analysis. It reads your code the way a person would, following the branches, the early returns and the assignments, and it keeps a running answer to the question: what can this variable be at this exact line? This post explains how that analysis works, which constructs feed it, how assignments and loops fit in, and the situations where it gives up. It describes TypeScript 6.x, and the analysis is the same in the native compiler preview that TypeScript 7 is built on. The reference is the handbook chapter on narrowing.
Declared type and narrowed type
Each variable has a declared type, the one in its annotation or inferred from its initializer. At each point in the program, the compiler computes a narrowed type, which is the declared type reduced by everything the code has established so far. Reading the variable gives the narrowed type. The declared type only limits what can be assigned to it.
function describe(x: string | number): string {
if (typeof x === "string") {
return x.toUpperCase();
}
return x.toFixed(1);
}
function broken(x: string | number): string {
return x.toUpperCase();
}basic.ts(8,12): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
Property 'toUpperCase' does not exist on type 'number'.In the first function, x is string inside the if body, because typeof x === "string" is true there. After the if, the body has returned, so the only way to reach the last line is when the test was false. Control flow analysis infers that x is number there, and toFixed is allowed. In the second function nothing narrows x, and the compiler reports the property that is missing on one member of the union.
What narrows a type
A handful of constructs act as narrowing guards. The typeof operator narrows primitives. The instanceof operator narrows to a class. The in operator narrows by property presence. Equality checks against literals and null narrow to those values, and truthiness tests remove null, undefined, 0, empty strings and false. A discriminant property check narrows a union of object types. A function that returns a type predicate narrows through its call. Each one produces a narrowed type on the true branch and the complementary type on the false branch.
type Result = { ok: true; value: number } | { ok: false; error: string };
function show(r: Result): string {
if (r.ok) {
return "value " + r.value;
}
return "error " + r.error;
}
function load(id: string | null): number {
if (id === null) {
return 0;
}
return id.length;
}(no output: the file compiles without errors)The check r.ok narrows the union by its discriminant: inside the if, r is the variant with ok: true, and after it, the other one. The check id === null removes null from the type in the code that follows the early return. No cast was needed in either function.
Narrowing by assignment
Assignments narrow too. When you assign a value to a variable declared with a union type, the narrowed type becomes the assigned type from that line on.
let x: string | number = "hello";
console.log(x.toUpperCase());
x = 42;
console.log(x.toFixed(1));
const s: string = x;assign.ts(7,7): error TS2322: Type 'number' is not assignable to type 'string'.On line 1 the declared type is string | number, and the assignment narrows x to string, so toUpperCase is allowed on line 2. On line 4 the assignment of 42 narrows x to number, so toFixed is allowed on line 5. On line 7 the narrowed type is still number, so using it as a string fails with the usual assignability error. If you remove the last line and run the program, it prints HELLO and then 42.0.
Narrowing by assignment is limited to declared union types. If a variable is declared as number, assigning a number does not make it more specific. An assignment also narrows to the type of the assigned value filtered by the declared union, so assigning a string to a string | number gives string, and not a particular literal.
Definite assignment
The same analysis tracks whether a variable has been assigned at all. A let declared without a value and read before it is set is an error, and the compiler follows branches to decide.
let label: string;
if (Math.random() > 0.5) {
label = "heads";
}
console.log(label);definite.ts(7,13): error TS2454: Variable 'label' is used before being assigned.The assignment happens on only one path, so on the other path label is unassigned at the console.log. Adding an else branch, or giving label an initial value, removes the error. This is flow analysis answering a different question from narrowing: not which type, but whether a value exists.
Loops and the fixed point
Loops make the analysis harder, because the type of a variable at the top of a loop depends on what happened at the bottom of the previous iteration. The compiler handles this by computing the type at the loop head as the union of the types arriving from before the loop and from the end of the body, and it repeats until the answer stops changing.
function firstLong(words: string[]): string | undefined {
let found: string | undefined = undefined;
for (const w of words) {
if (w.length > 5) {
found = w;
break;
}
}
return found;
}
console.log(firstLong(["cat", "elephant", "dog"]));elephantAt the return, found can be undefined, from the path where the loop finished without a match, or string, from the path through break. The declared return type covers both. You do not annotate anything inside the loop, and the compiler still gets the answer right.
Exhaustiveness and never
Control flow analysis also notices when a code path cannot be reached. When every member of a union has been handled, the remaining type is never, the type with no values. You can use this to make the compiler flag a missing case.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number }
| { kind: "triangle"; base: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.PI * s.radius * s.radius;
case "square":
return s.side * s.side;
default: {
const unreachable: never = s;
return unreachable;
}
}
}exhaustive.ts(13,13): error TS2322: Type '{ kind: "triangle"; base: number; }' is not assignable to type 'never'.The triangle case is not handled, so in the default branch s is still the triangle variant, and assigning it to never fails. The error is the reminder to add the case. When the union is complete, s is never there and the code compiles. Adding a new variant to the union later makes every such switch fail until it is updated, which is the benefit of the pattern.
Where narrowing is lost
Narrowing lasts as long as the compiler can prove nothing has changed the variable. Function boundaries are where that proof fails. A callback or a hoisted function may run at any later time, and a let variable could have been reassigned by then, so for such a variable the compiler goes back to the declared type.
let value: string | undefined = "abc";
if (value !== undefined) {
console.log(value.length);
function later(): number {
return value.length;
}
value = undefined;
}closure.ts(7,12): error TS18048: 'value' is possibly 'undefined'.Inside the if, value is narrowed to string, and the first use is fine. The function declaration runs in a different context, so it sees the declared type, and it is right to be careful, since the assignment after it shows the variable can in fact become undefined. Since TypeScript 5.4, narrowing is preserved in closures created after the last assignment to a let variable, which removes many false alarms. A const variable keeps its narrowing inside closures, because it can never be reassigned, which is one more reason to prefer const.
Other situations that drop narrowing include narrowing an object property after a function call that might change the object, narrowing across an await where other code can run, and narrowing a computed element access with a key that is not a literal.
interface Box {
item: string | null;
}
declare function mutate(b: Box): void;
function read(b: Box): number {
if (b.item === null) {
return 0;
}
mutate(b);
return b.item.length;
}(no output: the file compiles without errors)This one compiles, and that is worth knowing. TypeScript deliberately keeps property narrowing across a function call, because discarding it would make everyday code unbearable. The compiler trades soundness for convenience here: if mutate sets item to null, the program fails at run time with a type error from JavaScript, and the checker will not warn you. When a call might change the object, copy the property to a const first.
Practical guidance
Write the narrowing check, and let the compiler carry the result. Prefer early returns over deep nesting, because each return removes a possibility from the types that follow it. Prefer const for values you narrow, and copy a property into a local const before using it across a call. Use discriminated unions for variants, so that a single property test narrows the whole object.
When narrowing does not happen, ask what the compiler cannot prove. It is usually a function boundary, an await, or a mutation, and the fix is to restructure so the narrowing and the use are in the same stretch of code with no intervening change.
Common mistakes
The first mistake is casting with as to silence an error that narrowing would have fixed, which removes the compiler's protection. The second is checking truthiness on a value where 0 or an empty string is legitimate, so the guard narrows away a valid value. The third is relying on property narrowing across a call that mutates the object. The fourth is forgetting that a let captured by a hoisted function reverts to its declared type.
When this does not apply
Control flow analysis works within a function. It does not carry information between functions, so a function that checks a value and another that uses it will not share a narrowed type unless you pass the narrowed value along or use a type predicate. For data from outside the program, no analysis of your code can know what arrives, so validate it at run time first.


