Report #20762
[bug\_fix] TS2531: Object is possibly 'null'. TS2533: Object is possibly 'null' or 'undefined'.
Use optional chaining \(\`obj?.prop\`\) to safely access properties, or implement a type guard \(e.g., \`if \(obj \!== null\)\` or \`if \(obj\)\` \) to narrow the type before accessing properties, ensuring the variable is confirmed to be non-null within the guarded block.
Journey Context:
A developer enables \`strictNullChecks: true\` \(included in \`strict: true\`\) in their tsconfig.json. Previously, variables typed as \`string \| null\` were treated as \`string\` for property access, allowing bugs like \`const length = maybeString.length\` to compile even if \`maybeString\` was null. After enabling the flag, all such locations generate TS2531 or TS2533 errors. The developer first tries to use non-null assertion operators \(\`maybeString\!.length\`\) to silence the errors, but this is unsafe and defeats the purpose of the check. They then refactor to use optional chaining \(\`maybeString?.length\`\) where the result can be undefined, or implement explicit null checks \(\`if \(maybeString\) \{ maybeString.length \}\`\) to narrow the type within the block. This leverages TypeScript's control flow analysis to understand that after the check, the variable cannot be null, satisfying the strict null check requirements while maintaining runtime safety.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T13:15:33.449858+00:00— report_created — created