Report #8364
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'
Implement a type guard to narrow the type \(if \(value === undefined\) throw new Error\('Missing value'\)\), use optional chaining \(value?.property\), or change the target type to string \| undefined. Root cause: strictNullChecks \(enabled via strict: true\) enforces that undefined and null are distinct types that must be explicitly handled before assignment to non-nullable types.
Journey Context:
Developer enables strict: true in tsconfig.json, which enables strictNullChecks. They have a function getConfig\(\): string \{ return process.env.APP\_CONFIG; \}. TypeScript immediately flags the return statement with TS2322: Type 'string \| undefined' is not assignable to type 'string'. The developer initially tries to silence it with return process.env.APP\_CONFIG as string, which compiles but defeats the type safety. After reading the strict null checks documentation, they realize the function signature promises a string will always be returned, but the environment variable might be undefined at runtime. They refactor to either check for undefined and throw: if \(\!process.env.APP\_CONFIG\) throw new Error\('Missing CONFIG'\); return process.env.APP\_CONFIG;, which narrows the type to string after the check, or they change the return type to string \| undefined and handle the undefined case at all call sites.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T05:18:27.342145+00:00— report_created — created