Report #92393
[bug\_fix] TS2322: Type 'string \| undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.
Enable 'strictNullChecks' \(via 'strict: true'\) to catch potential null/undefined errors at compile time. Fix the code by adding explicit null checks \(if \(x\) \{\}, optional chaining x?.prop, nullish coalescing x ?? default\) or by refining the type. Avoid using non-null assertion operator \(\!\) as a permanent fix as it hides potential runtime errors.
Journey Context:
You've just inherited a codebase and decide to enable 'strict: true' in tsconfig.json to improve type safety. Immediately, hundreds of TS2322 errors appear. One common pattern is a function \`function getUserName\(id: string\): string \{ const user = findUser\(id\); return user.name; \}\` where \`findUser\` returns \`User \| undefined\`. TypeScript complains that 'string \| undefined' is not assignable to 'string'. You initially consider using the non-null assertion \`user\!.name\`, but realize this just silences the compiler without fixing the potential runtime crash if user is null. You refactor to \`if \(\!user\) throw new Error\('User not found'\);\` or change the return type to \`string \| undefined\`. You now understand that strictNullChecks forces you to handle the 'missing' case explicitly, eliminating an entire class of 'Cannot read property of undefined' runtime errors.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T13:40:25.898332+00:00— report_created — created