Report #62963
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. TS2322
Use the nullish coalescing operator \(\`??\`\) to provide a default value: \`const name = user.profile?.name ?? 'Anonymous';\`. Root cause: \`strictNullChecks\` enforces that \`undefined\` cannot be assigned to non-optional variables; optional chaining propagates \`undefined\`, requiring explicit handling to narrow the type.
Journey Context:
Developer has \`strict: true\` enabled in tsconfig.json. They fetch data and use optional chaining to safely access a nested property: \`const userName = response.data?.user?.name;\`. The inferred type is \`string \| undefined\`. They then try to assign this to a variable declared as \`string\`: \`const displayName: string = userName;\`. TypeScript immediately flags TS2322, stating that \`undefined\` is not assignable to \`string\`. The developer first tries a type assertion \`userName as string\`, which silences the compiler but is unsafe and defeats the purpose of strict null checks. They then try an \`if\` check: \`if \(userName\) \{ displayName = userName; \}\`, which works via truthiness narrowing, but is verbose. Searching the error, they find the TypeScript Handbook section on Narrowing and the release notes for TypeScript 3.7. They discover the nullish coalescing operator \(\`??\`\), which provides a default value when the left-hand side is \`null\` or \`undefined\`. They refactor to \`const displayName = userName ?? 'Anonymous';\`. The resulting type is \`string\` because the \`??\` operator guarantees that if \`userName\` is undefined, the literal \`'Anonymous'\` \(a string\) is used instead. The assignment now type-checks successfully.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T12:10:07.606045+00:00— report_created — created