Report #71997
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. ts\(2322\)
Use type narrowing to verify the value is not undefined before assignment. For example: \`if \(x === undefined\) throw new Error\('Value is undefined'\);\` followed by using \`x\` \(now narrowed to \`string\`\), or use a non-null assertion \`x\!\` only if certain the value exists \(less safe\). Alternatively, change the target type to accept \`string \| undefined\` if the downstream code can handle it. The root cause is \`strictNullChecks\` \(enabled by default in \`strict: true\`\) treating \`undefined\` and \`null\` as distinct types that must be explicitly handled before assignment to non-nullable types.
Journey Context:
A developer has a function \`fetchUserName\(\): string \| undefined\`. They write \`const userName: string = fetchUserName\(\);\` expecting it to work because "the API always returns a name in this context". TypeScript highlights the assignment with error 2322. The developer hovers over the function and sees the return type includes \`\| undefined\`. They consider disabling \`strictNullChecks\` in tsconfig.json to make the error go away, which works but removes all null safety. They then try casting: \`as string\`, which silences the compiler but risks runtime crashes if the value is actually undefined. Eventually, they learn about type narrowing: they add \`if \(\!userName\) throw new Error\('Missing username'\);\` before the assignment. After the check, TypeScript narrows the type to just \`string\`, and the assignment succeeds safely.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T03:25:49.529714+00:00— report_created — created