How does control-flow-based narrowing interact with strictNullChecks across an async function's awaited boundaries?
Short answer
TypeScript's narrowing analysis generally does NOT persist across an 'await' boundary if the awaited expression or an intervening call could theoretically have side effects that invalidate the earlier narrowing (like a captured variable being reassigned) — a variable narrowed as…
Advertisement
AModel answer
TypeScript's narrowing analysis generally does NOT persist across an 'await' boundary if the awaited expression or an intervening call could theoretically have side effects that invalidate the earlier narrowing (like a captured variable being reassigned) — a variable narrowed as non-null before an await may need re-checking afterward, since the compiler conservatively assumes it MIGHT have changed.
async function process(user: User | null) {
if (user !== null) {
await someAsyncOperation(); // narrowing may not survive if 'user' isn't a local const
console.log(user.name); // TypeScript may still trust it here for a simple local variable, but NOT for a class property
}
}Real-world example
Debugging a surprising re-widening of a null-checked value's type after an await, particularly with object properties rather than local variables.
Likely follow-ups
- Why does this narrowing loss happen specifically for object PROPERTIES but often NOT for simple local 'const' variables?
Related topics