Report #57168
[bug\_fix] Object is possibly 'null' \(TS2531\) or Object is possibly 'undefined'
With \`strictNullChecks\` enabled, values that include \`null\` or \`undefined\` in their type must be narrowed before accessing properties. Add a type guard: \`if \(element \!== null\)\` or use optional chaining \`element?.property\`. If certain the value exists \(e.g., immediately after \`document.getElementById\` where the element is guaranteed in the HTML\), use the non-null assertion \`element\!.property\` sparingly.
Journey Context:
Developer enables \`strict: true\` in a new TypeScript project for better type safety. They write \`const button = document.getElementById\('submit'\); button.addEventListener\('click', handler\);\`. TypeScript immediately flags \`button\` with 'Object is possibly null'. Developer is confused because the HTML definitely contains \`\`. They try \`if \(button\)\` but forget to return early, so TypeScript still complains in subsequent lines. They try casting \`\(button as HTMLElement\)\` which works but feels wrong. They discover optional chaining \`button?.addEventListener\`, but that changes logic \(no error thrown if missing\). They eventually read the TypeScript handbook on narrowing, realizing that \`getElementById\` returns \`HTMLElement \| null\` because the DOM might change or the ID might be wrong. They settle on \`if \(\!button\) throw new Error\('Missing \#submit'\);\` which narrows the type to \`HTMLElement\` for all subsequent code, satisfying both TypeScript and runtime safety.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T02:26:42.329377+00:00— report_created — created