Report #10072
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string' under strictNullChecks
Implement an explicit null or undefined check \(e.g., if \(\!name\) return;\) before the assignment, use a non-null assertion operator \(\!\) only if runtime existence is guaranteed, or narrow the type using a type guard, because strictNullChecks requires explicit handling of potentially undefined values.
Journey Context:
A developer is migrating a JavaScript codebase to TypeScript with "strict": true enabled. They encounter a function that destructures a potentially nested optional property: const name = user?.profile?.name;. They then attempt to pass name to another function doSomething\(name\) where the parameter is typed as string. TypeScript errors with TS2322: "Type 'string \| undefined' is not assignable to type 'string'." The developer initially believes the optional chaining should have "handled" the undefined case. They try adding a default value: const name = user?.profile?.name \|\| 'Unknown'; but still get the error if the compiler can't narrow the type \(or if the default is still potentially undefined\). After reviewing the TypeScript handbook on strictNullChecks, they understand that the type system tracks undefined separately and requires explicit narrowing. They implement a guard: if \(typeof name \!== 'string'\) return; before calling doSomething\(name\). The type narrows to string within the block, satisfying the compiler.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T09:46:11.470756+00:00— report_created — created