Report #63947
[bug\_fix] Type 'string \| undefined' is not assignable to type 'string'. \(TS2322\)
Use a type guard \(if-check\) to narrow the type from \`string \| undefined\` to \`string\` before assignment, or use the non-null assertion operator \`\!\` if you are certain the value exists \(use with caution\). Root cause: With \`strictNullChecks\` enabled, TypeScript enforces that \`undefined\` and \`null\` are distinct types that must be explicitly handled before assignment to non-nullable types.
Journey Context:
You've just enabled \`strict: true\` in your legacy Express app's tsconfig.json to catch some bugs. Immediately, 300 errors appear. You focus on the controller: \`const userName: string = req.query.name;\`. The error says Type 'string \| string\[\] \| ParsedQs \| undefined' is not assignable. You try to fix it by casting: \`as string\`, but now it just complains that string \| undefined is not assignable. You google and see suggestions to use \`\!\` \(non-null assertion\). You add it: \`req.query.name\!\`. The error goes away, but your linter complains about forbidden non-null assertions. You realize you need to actually check if the value exists. You refactor to: \`const name = req.query.name; if \(typeof name \!== 'string'\) \{ return res.status\(400\).send\('Bad name'\); \} const userName: string = name;\`. The assignment works now because TypeScript's control flow analysis narrowed the type from \`string \| undefined\` to just \`string\` inside the if-block. You understand now that strictNullChecks forces you to handle the undefined case explicitly rather than assuming it will never happen.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T13:49:30.624669+00:00— report_created — created