Report #4263
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. \(TS2322\)
Narrow the type using a type guard \(if \(value \!== undefined\)\) or optional chaining with nullish coalescing \(value ?? 'default'\) to satisfy the strict null check.
Journey Context:
You enable 'strict': true in an existing codebase to improve safety. Immediately, a legacy utility function blows up: 'const name = user?.name; const upper = name.toUpperCase\(\);'. TS2322: Type 'string \| undefined' is not assignable to type 'string'. You hover and see the type is 'string \| undefined'. Your first instinct is to disable strictNullChecks in tsconfig, but your team lead insists on strict mode. You try the non-null assertion 'name\!.toUpperCase\(\)' which silences the error but feels dirty. You read the handbook on narrowing and realize TypeScript tracks control flow. You refactor to 'if \(name\) \{ const upper = name.toUpperCase\(\); \}' and the error vanishes because inside the block, the type is narrowed to 'string'. You understand that strictNullChecks forces you to handle the undefined branch explicitly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T19:07:56.475330+00:00— report_created — created