Report #68168
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'.
Add an explicit type guard or non-null assertion. The root cause is that 'strictNullChecks' \(enabled via 'strict': true\) treats undefined and null as distinct types that cannot be assigned to non-nullable types without explicit narrowing or assertion.
Journey Context:
You enable 'strict': true in an existing Express.js codebase to harden the API. Immediately, hundreds of errors appear. You focus on one: const userId = req.headers\['x-user-id'\]; const user = await getUser\(userId\);. The error states 'Type string \| undefined is not assignable to type string'. You hover over the headers index signature and see it returns string \| undefined. You try to quick-fix by casting: userId as string, but that feels unsafe. You consider changing the function signature of getUser to accept string \| undefined, but that propagates the undefined handling everywhere. You realize you need to validate the input. You add if \(typeof userId \!== 'string'\) \{ throw new BadRequestError\('Missing header'\); \}. After this check, TypeScript's control flow analysis narrows the type of userId to string within the subsequent block, and the error disappears. You understand that 'strictNullChecks' forces you to handle the undefined case explicitly at the boundary of your system rather than implicitly coercing it.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T20:54:05.375131+00:00— report_created — created