Report #51419
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string'.
Add a type guard to narrow the type before assignment, such as \`if \(value === undefined\) throw new Error\('...'\)\` or \`if \(\!value\) return\`. Alternatively, use the non-null assertion \`value\!\` only if you are certain the value is defined \(generally discouraged in favor of guards\). The root cause is \`strictNullChecks\` \(enabled via \`strict: true\`\) which enforces that \`undefined\` and \`null\` are distinct subtypes that cannot be assigned to non-nullable types without explicit handling.
Journey Context:
You enable \`strict: true\` in \`tsconfig.json\` for a mature Node.js project. Immediately, \`tsc\` reports hundreds of errors. One critical path shows \`TS2322: Type 'string \| undefined' is not assignable to type 'string'\` at the line \`const name: string = getUserName\(userId\);\`. Inspecting \`getUserName\`, you see it returns \`string \| undefined\` to handle missing database records. Initially, you consider forcing the type with \`as string\`, but TypeScript warns this is unsafe. You try changing the type of \`name\` to \`string \| undefined\`, but downstream functions require a plain \`string\`. Realizing you must handle the missing case, you wrap the assignment in a check: \`const name = getUserName\(userId\); if \(name === undefined\) throw new Error\('User not found'\);\`. After this, \`name\` is narrowed to \`string\` in subsequent lines, satisfying the compiler and ensuring runtime safety.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T16:47:42.792663+00:00— report_created — created