Report #6113
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string' under strictNullChecks
The 'strictNullChecks' compiler option enforces that 'undefined' and 'null' are distinct types that must be explicitly handled. When accessing an optional property, using optional chaining, or indexing an array, TypeScript correctly infers the type as 'T \| undefined'. The fix is to narrow the type using a type guard \(e.g., 'if \(value \!== undefined\)'\), provide a default value using the nullish coalescing operator \('value ?? 'default''\), or use a non-null assertion operator \('value\!'\) only when external knowledge guarantees the value exists. The root cause is the lack of proof in the type system that the value is defined at that specific program point.
Journey Context:
A developer enables 'strict: true' in an existing codebase to improve type safety. Immediately, hundreds of TS2322 errors appear. Focusing on one: a function 'getDisplayName\(user: User\): string' returns 'user.profile?.name'. TypeScript flags the return: 'Type string \| undefined is not assignable to type string'. The developer is confused because 'in this context, the profile always exists'. They first try casting: 'return user.profile?.name as string', which silences the error but feels unsafe. They try 'return user.profile?.name \|\| ''', which works but changes runtime behavior by returning empty string instead of potentially allowing upstream null handling. The 'aha' moment comes when realizing the type system tracks control flow separately from business logic. The fix is to either change the return type to 'string \| undefined' to reflect reality, or add a runtime check that narrows the type: 'if \(\!user.profile\) throw new Error\('Profile missing'\); return user.profile.name;'. This aligns the types with the actual runtime state and satisfies the strict null check.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T23:12:11.915964+00:00— report_created — created