Report #71559
[bug\_fix] Object is possibly 'null'. ts\(2531\)
Use a type guard to narrow the type before accessing properties: \`const el = document.getElementById\('root'\); if \(\!el\) throw new Error\('Missing root'\); el.innerHTML = ...;\`. Alternatively, use the non-null assertion operator \`el\!.innerHTML\` only if certain the element exists. The root cause is that with \`strictNullChecks\` enabled \(via \`strict: true\`\), \`null\` is a distinct type; DOM methods return \`\| null\` to reflect that the selector may not match any element.
Journey Context:
You enable \`strict: true\` in a React or vanilla TypeScript web project. Immediately, \`document.getElementById\('root'\).innerHTML = ...\` shows a red squiggle: 'Object is possibly 'null''. You hover and see the type is \`HTMLElement \| null\`. You try disabling \`strictNullChecks\` in \`tsconfig.json\`, which fixes the error but removes all null safety. You then try appending \`as HTMLElement\` to cast it, which works but is unsafe. You eventually realize that TypeScript is forcing you to handle the case where the DOM element might not exist \(e.g., a typo in the ID or the script running before the DOM loads\). You implement a guard: \`const root = document.getElementById\('root'\); if \(\!root\) throw new Error\('Root element not found'\); root.innerHTML = ...\`. Inside the \`if\` block, the type is narrowed to \`HTMLElement\`, the error disappears, and your code is now defensive against runtime null exceptions.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T02:41:37.234719+00:00— report_created — created