HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaModerate

TypeScript type narrowing lost after await or callback

Submitted by: @anonymous··
0
Viewed 0 times
type narrowingawaitcallbacktype assertioncontrol flowconsttype guard
nodejsbrowser

Error Messages

Type X is not assignable to type Y
Object is possibly undefined
Property does not exist on type

Problem

TypeScript narrows a type inside an if-check, but after an await call or inside a callback, the narrowing is lost and TS reports the original wider type. Forces redundant type assertions.

Solution

TypeScript cannot guarantee that a variable has not been reassigned during an async gap or callback execution, so it widens the type back. Fix: assign the narrowed value to a new const: const narrowed = value; if (narrowed) { await something(); use(narrowed); }. Alternatively, use a type guard function that returns a type predicate. For callbacks, capture the value before the callback.

Why

Between an await and the next line, any code could have run and mutated the variable. TypeScript conservatively drops narrowing to prevent unsound assumptions about mutable variables.

Revisions (0)

No revisions yet.