Type narrowing lost after assignment
Quick summary
You narrowed a type in an if block, but after assigning to a variable, the narrowing is lost — the variable has the wide type.
Why this happens
A narrowed value is assigned to a variable declared with the wider type, losing the narrowing
A function call between the narrowing and the use causes TypeScript to widen the type back
The narrowing is based on a property check, but the object is reassigned, invalidating the narrowing
Minimal example
let value: string | number = getValue();
if (typeof value === 'string') {
// value is string here
const stored = value; // string
}
console.log(value.toUpperCase()); // error: value is string | numberlet value: string | number = getValue();
if (typeof value === 'string') {
console.log(value.toUpperCase()); // safe: narrowed to string
}
// Or use a type guard:
function isString(x: unknown): x is string { return typeof x === 'string'; }
if (isString(value)) { console.log(value.toUpperCase()); } // narrowedUsing the narrowed value inside the if block keeps the type narrowing valid, or a type predicate function preserves narrowing across calls.
How to diagnose
Hover over the variable after the assignment to see if the type was widened back
Check if there are function calls between the narrowing and the use that could invalidate it
Use a type guard function that returns a type predicate to maintain narrowing across assignments
How to fix
Use a type predicate function (x is string) to maintain narrowing: function isString(x: any): x is string
Assign the narrowed value to a new variable with the narrowed type explicitly annotated
Move the code that uses the narrowed type inside the if block where the narrowing is still valid
How to prevent
Use type guard functions with type predicates for reusable narrowing that survives assignments
Keep narrowed code inside the narrowing block rather than extracting to variables with wider types
Related Resources
Related Glossary
Related Lessons
- Type Narrowing
Learn about type narrowing.