Report #5796
[bug\_fix] error TS2322: Type 'string \| undefined' is not assignable to type 'string'.
Use a type guard to narrow the type before assignment: \`if \(typeof value === 'string'\) \{ /\* assign here \*/ \}\`, or provide a default value using the nullish coalescing operator: \`const str = value ?? 'default'\`. Alternatively, if certain the value is defined \(e.g., initialized earlier\), use a non-null assertion \`value\!\` \(use sparingly\). The root cause is that \`strictNullChecks\` \(enabled via \`strict: true\`\) distinguishes between \`string\` and \`string \| undefined\`. The type system correctly tracks that a variable might be undefined at runtime, preventing unsafe operations that would cause runtime errors like \`Cannot read property 'toUpperCase' of undefined\`.
Journey Context:
Developer enables \`strict: true\` in tsconfig.json to improve type safety. Immediately, dozens of TS2322 errors appear where functions return \`string \| undefined\` \(e.g., \`array.find\(\)\` or optional chaining \`user?.name\`\) but the result is assigned to a \`string\` variable or passed to a function expecting \`string\`. Developer attempts to fix by checking \`if \(user.name\)\` before use, but the error persists if the variable is reassigned later or captured in a closure \(TypeScript invalidates narrowing for mutable variables used in closures\). Developer considers disabling \`strictNullChecks\` but that defeats the purpose. They try casting with \`as string\` which works but is unsafe. Eventually, they learn to use the nullish coalescing operator \`const name = user.name ?? 'Unknown'\` for defaults, or explicit type guards \`if \(typeof user.name === 'string'\)\` for blocks of code. For immutable checks, \`const\` assertions help preserve narrowing.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T22:12:55.543287+00:00— report_created — created