Report #20994
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string' when assigning a value from an optional property or a querySelector result.
Implement a type guard \(e.g., \`if \(value \!== undefined\)\` or \`if \(value\)\`\), use the non-null assertion operator \(\`value\!\`\) when certain of runtime state, or refactor to handle the undefined case explicitly. Root cause: With \`strictNullChecks: true\` \(enabled by default in \`strict\` mode\), TypeScript treats \`null\` and \`undefined\` as distinct types that are not assignable to other types unless explicitly unioned \(\`string \| null\`\). This prevents dereferencing null/undefined at runtime. The fix narrows the type through control flow analysis \(type guard\) or asserts the non-nullability when the developer has external knowledge that the value is safe.
Journey Context:
Developer upgrades an existing JavaScript codebase to TypeScript with \`strict: true\`. They have a function \`getUserName\(userId: string\): string\` that calls \`fetch\` and returns \`data.name\`. The fetch might return null if the user isn't found. The compiler throws \`TS2322: Type 'string \| undefined' is not assignable to type 'string'\`. The developer tries to fix it by casting: \`return data.name as string\`, which silences the error but doesn't fix the potential runtime crash. They try \`return data.name \|\| ''\` which works but might hide errors. They read the TypeScript handbook on 'Strict Null Checks' and realize they need to handle the undefined case properly. They refactor the function to return \`string \| null\` and update the caller to check \`if \(name === null\)\` before using the value. This propagates the type safety upstream and eliminates the error correctly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T13:38:41.287378+00:00— report_created — created