Report #90050
[bug\_fix] TS2532: Object is possibly 'undefined' inside a callback despite narrowing check outside
Capture the narrowed value in a 'const' variable inside the narrowing block before entering the closure, ensuring the value is frozen at that point.
Journey Context:
Developer writes 'if \(user\) \{ setTimeout\(\(\) => console.log\(user.name\), 1000\); \}'. TypeScript reports that 'user' is possibly undefined inside the arrow function. The developer is confused because they explicitly checked 'if \(user\)'. They try adding a non-null assertion 'user\!.name', which silences the error but feels unsafe. Investigating further, they learn that TypeScript's control flow narrowing does not persist across function boundaries because the closure could be executed later, after 'user' has been reassigned or cleared. The correct pattern is to capture the current value: 'if \(user\) \{ const currentUser = user; setTimeout\(\(\) => console.log\(currentUser.name\), 1000\); \}'. This creates a 'const' binding that is definitively not null within the closure.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T09:44:39.534297+00:00— report_created — created