Report #61757
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string' \(or similar for custom types\) within a closure or callback, despite an outer if-check confirming the value is defined.
Capture the narrowed value into a \`const\` variable within the same block scope before entering the closure, or use the non-null assertion operator \`\!\` with a justification comment. Root cause: TypeScript's control flow analysis does not narrow variables across closure boundaries because the variable could be reassigned before the closure executes.
Journey Context:
You fetch user data: \`let user = await getUser\(\);\`. You check \`if \(user\) \{ setTimeout\(\(\) => \{ sendEmail\(user.email\); \}, 0\); \}\`. TypeScript highlights \`user.email\` with 'user is possibly null'. You're baffled because you checked \`if \(user\)\`. You hover over \`user\` inside the callback and see \`User \| null\`. You realize the closure captures the variable, not the value, and \`user\` could theoretically be set to null before the timeout runs. The fix clicks: you declare \`const currentUser = user;\` inside the \`if\` block, before the setTimeout. Inside the callback, you use \`currentUser.email\`. TypeScript is happy because \`const\` cannot be reassigned, so the narrowing is preserved.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T10:08:55.992454+00:00— report_created — created