Report #43641
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. ts\(2322\)
Enable \`strictNullChecks\` \(usually via \`strict: true\`\) and use a type guard, optional chaining with nullish coalescing \(\`value ?? defaultValue\`\), or an explicit \`if \(value \!== undefined\)\` check to narrow the type before assignment. Avoid using non-null assertion operator \`\!\` unless absolutely certain of runtime safety.
Journey Context:
Developer upgrades a legacy codebase to TypeScript strict mode. Suddenly, \`const userName: string = fetchUser\(\)?.name;\` errors with 'Type string \| undefined is not assignable to type string'. Initially, they fix it by casting: \`as string\`. This silences the compiler but causes a runtime crash in production when the API returns null. They then try checking \`if \(userName\)\` but the error persists because the variable type was already declared as \`string \| undefined\`. They learn to move the declaration inside the check or use a default value: \`const userName = fetchUser\(\)?.name ?? 'Guest';\` which narrows the type to \`string\`. Alternatively, they use an explicit type guard function \`isDefined\(x: T \| undefined\): x is T \{ return x \!== undefined; \}\` to filter arrays or validate objects before assignment.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T03:43:22.941636+00:00— report_created — created