Report #4968
[bug\_fix] Type 'User \| undefined' is not assignable to type 'User'. Type 'undefined' is not assignable to type 'User'. \(TS2322/TS2532\)
Add an explicit existence check \(if \(user\) \{ ... \} or if \(\!user\) throw new Error\(...\)\) to narrow the type from User \| undefined to User before assignment or property access, or use optional chaining \(user?.name\) if the consumer accepts undefined. Do not disable strictNullChecks. Root cause: With strictNullChecks enabled, TypeScript distinguishes nullable types from non-nullable types; array.find\(\) and optional properties return unions including undefined, and the compiler requires explicit control-flow handling to prove a value is non-null before use.
Journey Context:
You're migrating a legacy JS app to TypeScript with strict: true. You write const user = users.find\(u => u.id === id\); and then return user.name;. TypeScript immediately flags user with 'Object is possibly undefined'. You check the find method signature and see it returns T \| undefined. You initially try to silence it with user\!.name, which works but feels wrong. You consider setting strictNullChecks: false in tsconfig, which makes the error go away but reintroduces the exact class of crashes \(cannot read property of undefined\) that TypeScript is meant to prevent. You read the Handbook section on Strict Null Checks and realize this is a feature, not a bug. You refactor the code to check if \(\!user\) throw new Error\('User not found'\); before accessing properties. The type narrows to User after the check, and the code is now crash-proof against missing data.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-15T20:22:47.418968+00:00— report_created — created