Sub topic 14
When Narrowing Is Lost: Callbacks, Mutation, and Aliasing
This chapter assumes you know basic TypeScript syntax, union types such as string | number, and the narrowing checks from earlier chapters (typeof, equality, in, instanceof, discriminated unions, and type predicates). Here you will learn where the compiler stops trusting a narrowed type, why it stops, and how to restructure code so narrowing survives.
Why narrowing can be lost
TypeScript narrows a value by following the control flow of your code. After if (x !== undefined), the compiler knows x is not undefined in that branch, as long as nothing between the check and the use could change x.
The compiler cannot run your program. It makes a trade-off between two goals:
- Be useful, by remembering a narrowed type as long as possible.
- Be safe, by forgetting a narrowed type when something might have changed the value.
Narrowing is lost in three common situations: a callback runs later, a value is mutated, or a value is reached through an alias or a property path the compiler cannot track.
Callbacks and mutable properties
Consider an object with an optional property. You check the property, then use it inside a callback.
function scheduleLogBroken(user: { name?: string }): void {
if (user.name !== undefined) {
setTimeout(() => {
// Error: 'user.name' is possibly 'undefined'.
console.log(user.name.toUpperCase());
}, 100);
}
}The check is correct when it runs. But the callback runs 100 milliseconds later. In that time, other code could have set user.name = undefined. Because user is an object whose properties can be reassigned, the compiler discards the narrowing inside the function expression.
The fix is to copy the value into a const. A const cannot be reassigned, so its narrowed type is safe in any callback.
function scheduleLog(user: { name?: string }): void {
const name = user.name;
if (name !== undefined) {
setTimeout(() => {
console.log(name.toUpperCase());
}, 100);
}
}The copy holds a string after the check, and nothing can change it. This pattern works for any callback: setTimeout, Array.prototype.map, event handlers, and promise .then functions.
`let` variables and reassignment
The same rule applies to variables declared with let. If a let variable is assigned anywhere after the check, a callback may see a different value from the one you checked.
function demoLet(input: string | null): void {
let value = input;
if (value !== null) {
const lengths = [1, 2, 3].map((n) => {
// Error: 'value' is possibly 'null'.
return value.length + n;
});
console.log(lengths);
}
value = null;
}Because value = null appears later in the function, the compiler treats value as changeable and drops the narrowing in the callback. If you remove the later assignment, or use const, the error disappears.
Recent TypeScript versions (5.4 and later) keep narrowing in closures created after the last assignment to a let variable or parameter. This helps when the reassignment happens before the check. It does not help in the example above, where an assignment comes after the callback is created.
function demoParam(input: string | null): void {
if (input === null) {
return;
}
// No assignments to `input` follow, so TypeScript 5.4+ keeps it as string here.
const lengths = [1, 2, 3].map((n) => input.length + n);
console.log(lengths);
}Note that parameters and const variables have long kept their narrowing in callbacks when they were never reassigned. If you target an older compiler, copy to a const to be safe.
Function calls do not reset variable narrowing
TypeScript does not assume that calling a function resets the narrowing of a local variable or a property. This is a deliberate choice for usability, and it means the compiler can be wrong.
type Box = { value: string | number };
function clear(box: Box): void {
box.value = 0;
}
function risky(box: Box): string {
box.value = "text";
clear(box);
// The compiler still thinks box.value is a string.
return box.value.toUpperCase();
}This code compiles, but at runtime box.value is 0, and toUpperCase throws a TypeError. The assignment box.value = "text" narrowed the property to string. The call to clear changed it, but the compiler does not track what a called function does.
This is a known gap, not a bug you can configure away. The practical defense is to keep narrowed property accesses short-lived: read the property into a const right before you use it, and avoid calling functions that mutate the same object between a check and a use.
Aliasing: narrowing a copy does not narrow the original
An alias is a second name for the same value. TypeScript narrows the name you checked, not other names that point to the same thing.
type Result = { ok: true; data: string } | { ok: false; error: string };
function readAlias(result: Result): string {
const other = result;
if (result.ok) {
// `result` is narrowed here. `other` is still the full union.
return other.ok ? other.data : "unreachable";
}
return result.error;
}The check on result does not change the type of other. If you wrote other.data directly, the compiler would report an error. Check the name you intend to use, or use the narrowed name everywhere.
TypeScript does support one form of aliasing: a const that stores the result of a condition. This is called an aliased condition.
type Pet = { kind: "dog"; bark(): void } | { kind: "cat"; purr(): void };
function speak(pet: Pet): void {
const isDog = pet.kind === "dog";
if (isDog) {
pet.bark();
} else {
pet.purr();
}
}This works because isDog is a const and pet is a parameter that is never reassigned. If pet were a let variable that is later reassigned, the narrowing through isDog would be lost.
Destructuring and narrowing
Destructuring a discriminated union into separate variables used to break the link between the discriminant and the other fields. Modern TypeScript (4.6 and later) keeps the link when the variables come from a const destructuring of a union with a literal discriminant.
type Action =
| { kind: "add"; amount: number }
| { kind: "reset" };
function apply(action: Action, total: number): number {
const { kind } = action;
if (kind === "add") {
return total + action.amount;
}
return 0;
}This only works under the same conditions as other aliasing: kind is a const, and action is not reassigned. If you rely on this and still see errors, check which TypeScript version your project uses.
Mutation inside a branch
Assignment itself also changes narrowing. After you assign a value to a variable, TypeScript narrows the variable to the type of the assigned value, within the declared type.
function demoAssign(): void {
let id: string | number = "abc";
id.toUpperCase(); // OK: narrowed to string by the assignment
id = 42;
id.toFixed(2); // OK: now narrowed to number
}Assignment narrowing only works within the declared type. If you declare let id: string | number, the compiler allows assignments of either type and tracks which one was last assigned. If you declare let id = "abc", the declared type is string, and assigning 42 is an error.
Strategies for keeping narrowing
When the compiler loses narrowing, restructure the code rather than reaching for a type assertion (as). An assertion silences the error but also silences the safety check.
- Copy to a
constbefore the check, and use the copy afterwards. - Return early on the failing case, so the rest of the function sees the narrowed type.
- Pass the narrowed value into a helper function as an argument. A parameter has its own type, which does not depend on the caller's narrowing.
- Avoid reassigning variables that you narrow and later capture in callbacks.
- Keep the gap between a check and its use short, and avoid calling unknown functions between them.
The helper function approach is useful when a block of code needs a non-null value:
function printUpper(text: string): void {
console.log(text.toUpperCase());
}
function process(user: { name?: string }): void {
if (user.name !== undefined) {
printUpper(user.name);
}
}Here user.name is used directly after the check, with no callback in between, so narrowing holds.
Common mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| Using `obj.prop` in a callback after checking it | Properties can be reassigned before the callback runs | Copy to a `const` first |
| Capturing a `let` variable that is reassigned later | The compiler cannot tell which value the callback sees | Use `const`, or stop reassigning |
| Narrowing one name and using its alias | Narrowing applies to the checked name only | Use the checked name |
| Assuming a function call keeps a property safe | The compiler does not model side effects of calls | Re-read the property into a `const` after the call |
| Using `as` to remove the error | Hides a real risk of `undefined` at runtime | Restructure so the compiler can follow |
Exercises
Exercise
The function below reports "'config.timeout' is possibly 'undefined'" inside the callback, even though the if checks it. Rewrite it so it compiles without using as or !.
function retry(config: { timeout?: number }): void {
if (config.timeout !== undefined) {
setTimeout(() => console.log(config.timeout.toFixed(0)), 10);
}
}
Show answer
Copy the property into a const and check the copy: function retry(config: { timeout?: number }): void { const timeout = config.timeout; if (timeout !== undefined) { setTimeout(() => console.log(timeout.toFixed(0)), 10); } } The const cannot be reassigned, so its narrowed type number stays valid inside the callback. The original fails because config.timeout is a mutable property that could change before the callback runs.
Exercise
In the code below, the compiler accepts the last line, but the program throws at runtime. Explain why, and name one change that reduces the risk. type Box = { value: string | number }; function reset(box: Box): void { box.value = 0; } function run(box: Box): string { box.value = "hi"; reset(box); return box.value.toUpperCase(); }
Show answer
The assignment narrows box.value to string, and TypeScript does not reset that narrowing after the call to reset. At runtime reset sets the value to 0, so toUpperCase fails with a TypeError. To reduce the risk, avoid relying on the earlier narrowing: after the call, read the property again and check it, for example with if (typeof box.value === "string"), or avoid mutating the same object in a helper.