Report #61336
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string'.
Use a type guard \(if-check\), the nullish coalescing operator \(??\), or provide an explicit default value to narrow the type before assignment, rather than using 'as string' or the non-null assertion '\!'.
Journey Context:
The developer writes 'const name = process.env.USER\_NAME' and passes it to a function 'greet\(name: string\)'. TypeScript highlights it: 'Type 'string \| undefined' is not assignable'. The developer thinks, 'I know this env var is set in production,' and silences the error with 'name as string' or 'name\!'. The code compiles and ships. In production, when the env var is missing, the app crashes at runtime. The developer returns to the code, realizing that 'strictNullChecks' is forcing them to handle the undefined case explicitly. They try 'if \(name\) greet\(name\)'—this works because the type guard narrows 'string \| undefined' to 'string' within the block. Alternatively, they use 'greet\(name ?? 'Anonymous'\)', using nullish coalescing to guarantee a string. The fix works because it satisfies the compiler's requirement for a definite string type while actually handling the runtime possibility of undefined.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T09:26:05.805313+00:00— report_created — created