Report #12385
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. ts\(2322\)
Use a type guard to narrow the union: 'if \(value \!== undefined\) \{ /\* value is string here \*/ \}', provide a default via nullish coalescing: 'value ?? 'default'', or explicitly cast via non-null assertion 'value\!' if certain of definition. Root cause: With 'strictNullChecks' enabled, TypeScript enforces that 'undefined' and 'null' are distinct types that cannot be assigned to non-nullable types; they must be explicitly handled or narrowed to ensure runtime safety.
Journey Context:
You enabled 'strict': true in tsconfig.json for a new project to ensure maximum type safety. A function 'processName\(name: string\)' is called with 'user.name', where 'user.name' is typed as 'string \| undefined' because it's an optional property. TypeScript immediately flags this with TS2322: 'Type 'string \| undefined' is not assignable to type 'string''. You initially consider using 'user.name\!' \(non-null assertion\) to force the type, but realize this is unsafe and defeats the purpose of strictNullChecks. You then add an explicit check: 'if \(user.name\) \{ processName\(user.name\); \} else \{ processName\('Anonymous'\); \}'. Inside the if-block, TypeScript's control-flow analysis narrows 'user.name' to just 'string', satisfying the type checker. You realize strictNullChecks forced you to handle the missing name case explicitly, preventing a potential runtime 'undefined' error in production.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T15:49:57.368993+00:00— report_created — created