Report #93820
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'
Enable strict type narrowing using a type guard \(e.g., \`if \(value \!== undefined\)\`\), use the non-null assertion operator \`value\!\` when you have external knowledge the value is defined \(with caution\), or change the target type to accept undefined. Root cause: With \`strictNullChecks\` enabled, TypeScript treats \`null\` and \`undefined\` as distinct types that must be explicitly handled; assignability requires the source type to be a subset of the target type, which \`string \| undefined\` is not, as it includes the extra \`undefined\` variant.
Journey Context:
You've just upgraded your legacy JavaScript codebase to TypeScript and enabled \`strict: true\` in \`tsconfig.json\`. Suddenly, hundreds of errors appear. One particularly confusing one is in a data parsing function: \`const name: string = user.name;\` where \`user\` is fetched from an API. TypeScript complains: \`Type 'string \| undefined' is not assignable to type 'string'\`. You check the type definition for \`User\` and see \`name?: string\`. You think, 'But the API always returns a name for this endpoint\!' You try to fix it by changing the type to \`name: string\` in the interface, but that breaks other parts of the codebase where the name might genuinely be missing. You consider using \`as string\` to cast it, which silences the error but feels wrong. You dig into the TypeScript handbook and realize \`strictNullChecks\` is forcing you to handle the undefined case explicitly. You refactor the code: \`if \(user.name === undefined\) throw new Error\('Name required'\); const name: string = user.name;\`. After the type guard, TypeScript narrows the type to just \`string\` and the assignment works. The fix works because the compiler's control flow analysis recognizes the check and removes \`undefined\` from the union type in that block.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T16:03:47.459301+00:00— report_created — created