Report #40045
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. TS2322.
Add an explicit type guard to narrow the type before assignment \(e.g., \`if \(value \!== undefined\) \{ target = value; \}\`\), or use the non-null assertion operator \(\`value\!\`\) if certain the value is defined. Alternatively, change the target type to accept \`undefined\` or provide a default using nullish coalescing: \`target = value ?? 'default'\`. Root cause: \`strictNullChecks\` \(enabled via \`strict: true\`\) enforces that \`null\` and \`undefined\` are distinct types that cannot be assigned to non-nullable types without explicit handling.
Journey Context:
Developer enables \`strict: true\` in an existing codebase. A function \`findUser\(id\): User \| undefined\` returns a user or undefined. The developer writes \`const user: User = findUser\('123'\);\`. TypeScript immediately flags \`Type 'User \| undefined' is not assignable to type 'User'\`. The developer initially tries to cast using \`as User\`, which silences the error but feels unsafe. They realize that with \`strictNullChecks\`, the type system forces them to handle the undefined case explicitly. They refactor to check if the user exists: \`const user = findUser\('123'\); if \(\!user\) throw new Error\('Not found'\); sendEmail\(user\);\`. Inside the \`if\` block, TypeScript narrows the type to \`User\`, satisfying the check. The developer understands that the fix works because the type guard removes \`undefined\` from the union type, aligning with the strict null safety requirements.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:41:18.923789+00:00— report_created — created