Report #16452
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string' \(strictNullChecks\)
Narrow the type using a control flow guard \(e.g., \`if \(value \!== undefined\)\`\), use optional chaining with a nullish coalescing default \(\`value ?? 'default'\`\), or update the target type to accept undefined. Do not use non-null assertion \(\`\!\`\) unless provably safe.
Journey Context:
You enabled \`strict: true\` \(specifically \`strictNullChecks\`\) in your legacy Node.js API server to improve safety. Immediately, \`const userName = req.user?.name; func\(userName\);\` throws TS2322 because \`userName\` is \`string \| undefined\` but \`func\` expects \`string\`. You check \`req.user\` and see it can indeed be null if the auth middleware failed. You consider \`as string\` or \`\!\` to silence it, but realize that could cause runtime crashes. You instead wrap the call in \`if \(userName\) \{ func\(userName\); \}\` or change the call to \`func\(userName ?? 'Anonymous'\)\`. This satisfies the compiler by narrowing the union type to just \`string\` before the call.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T02:44:12.438866+00:00— report_created — created