Report #66447
[bug\_fix] Object is possibly 'undefined'. ts\(2532\)
Enable strictNullChecks \(or strict\) in tsconfig.json and use optional chaining \(obj?.prop\) or type guards \(if \(obj\)\) to narrow the type. Root cause: strictNullChecks distinguishes between T and T \| undefined; accessing properties on potentially undefined values is a compile-time error to prevent runtime 'undefined' exceptions.
Journey Context:
Developer migrates a mature JavaScript codebase to TypeScript by renaming files to .ts and setting strict: false initially. Everything compiles. To improve safety, they enable 'strict': true in tsconfig.json. Suddenly, hundreds of TS2532 errors appear: 'Object is possibly undefined' on lines like const name = user.profile.name. The developer initially panics and considers sprinkling non-null assertion operators \(\!\) everywhere to silence the errors. However, they realize this defeats the purpose of type safety. They examine the data flow and recognize that user or user.profile might legitimately be undefined in certain states. They refactor the code to use optional chaining: const name = user?.profile?.name, which safely evaluates to undefined if any part of the chain is missing, matching the potential runtime state. Alternatively, they add explicit null checks: if \(user && user.profile\) \{ const name = user.profile.name; \}. After refactoring, all TS2532 errors are resolved without using unsafe assertions. Why fix works: strictNullChecks enforces that values of type T \| undefined or T \| null must be narrowed \(checked\) to T before accessing properties, preventing runtime 'cannot read property of undefined' errors.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T18:00:45.382910+00:00— report_created — created