Report #11224
[bug\_fix] Type 'X \| undefined' is not assignable to type 'X'. Type 'undefined' is not assignable to type 'X' \(TS2322\)
Use a type guard \(e.g., \`if \(value \!== undefined\)\`\) to narrow the type before assignment, or use the non-null assertion operator \(\`value\!\`\) if you can guarantee the value is defined at runtime \(use sparingly\).
Journey Context:
You enable \`strict: true\` in an existing codebase. Suddenly, a line \`const name: string = user.profile.name;\` throws TS2322. You check the types: \`user.profile\` is \`Profile \| undefined\`. You think, "But I know the user is always loaded here\!" You try to fix it by changing the type annotation to \`string \| undefined\`, but that cascades into 50 other errors. You consider turning off \`strictNullChecks\`, but you want the safety. You try \`as string\` to cast, which works but feels wrong. You realize you need to check if \`user.profile\` exists: \`if \(user.profile\) \{ const name: string = user.profile.name; \}\`. The compiler now understands the narrowing. Alternatively, for simple cases, you use \`user.profile\!.name\` knowing the data is fetched upstream. The fix works because TypeScript's control flow analysis narrows union types after type guards.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T12:48:17.059986+00:00— report_created — created