Report #103447
[bug\_fix] Object is possibly 'null'. ts\(2531\)
Add an explicit narrowing check before using the value: 'if \(element \!== null\) \{ ... \}', use optional chaining \('element?.value'\), or provide a non-null default \('element ?? defaultValue'\). Avoid the non-null assertion operator \('\!'\) unless you have a runtime guarantee.
Journey Context:
A React component called 'document.getElementById\('root'\)' and immediately called '.appendChild\(\)'. With 'strictNullChecks' enabled, TypeScript flagged the element as 'HTMLElement \| null'. I first tried 'as HTMLElement' casting, which silenced the compiler but could throw at runtime if the ID was missing or the script ran in the wrong order. I then wrapped the call in 'if \(root\)', which removed the error and matched the actual runtime invariant. The fix works because 'strictNullChecks' treats 'null' and 'undefined' as distinct types in the type system; TypeScript only narrows the union away after a control-flow check proves the value is non-null.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-11T04:25:13.056507+00:00— report_created — created