Report #91359
[bug\_fix] TS2532: Object is possibly 'undefined' \(when accessing result of Array.prototype.find\(\)\)
Use optional chaining \(user?.name\) to safely handle the undefined case, implement a type guard with an explicit if-check or assertion to narrow the type from 'T \| undefined' to 'T', or use the non-null assertion operator \(user\!.name\) only when certain of existence \(with caution\).
Journey Context:
You're iterating over a user directory fetched from an API. You write 'const admin = users.find\(u => u.role === 'admin'\); console.log\(admin.email\);'. TypeScript immediately flags 'admin' with 'Object is possibly 'undefined''. You think, 'But the database always has an admin\!' You try adding 'if \(\!admin\) return;' but TypeScript still complains in the next line because you forgot to actually return or use the narrowed variable. You try using the non-null assertion operator 'admin\!.email', which silences the error but feels unsafe. You check tsconfig and see 'strictNullChecks: true'. The rabbit hole reveals that 'Array.prototype.find' returns 'T \| undefined' by ECMAScript spec, and strictNullChecks forces you to handle that union instead of ignoring the undefined possibility. The 'aha' moment comes when you realize TypeScript is modeling JavaScript's runtime behavior—find returns undefined if no match is found. The fix is either a type guard with an explicit throw/return, using optional chaining 'admin?.email' if you want to propagate undefined, or refactoring to a data structure that guarantees existence.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T11:56:28.158450+00:00— report_created — created