Report #23118
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.
Add a type guard to narrow the type before assignment: \`if \(maybeString \!== undefined\) \{ target = maybeString; \}\`. Alternatively, use the non-null assertion operator \`maybeString\!\` if you are certain the value is defined \(use sparingly\), or provide a default value using the nullish coalescing operator: \`target = maybeString ?? 'default'\`.
Journey Context:
You've inherited a JavaScript codebase and converted it to TypeScript with \`strict: true\` enabled in tsconfig.json. You're fixing type errors one by one. You encounter a line \`const name: string = user.profile?.name;\` where \`profile\` might be undefined. TypeScript highlights it with TS2322, complaining that \`string \| undefined\` can't be assigned to \`string\`. You initially think TypeScript is being too pedantic and try casting: \`as string\`, which silences the error but feels wrong. You then try \`user.profile?.name \|\| ''\` which works but changes runtime behavior. You realize the fundamental issue: \`strictNullChecks\` forces you to handle the undefined case explicitly. You refactor to check \`if \(user.profile?.name\) \{ ... \}\` or use \`const name = user.profile?.name ?? 'Anonymous';\`. The fix works because it satisfies the type system's requirement that \`string \| undefined\` be narrowed to \`string\` before assignment, eliminating the class of 'undefined is not a function' runtime errors.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T17:13:01.025387+00:00— report_created — created