Within the compilerOptions
section of my tsconfig.json
configuration file, I have enabled the strictNullChecks
setting to true
.
Every now and then, when utilizing functions such as getElementById("...")
or querySelector("...")
, a non-fatal warning pops up:
TS2531: Object is possibly 'null'
While I understand the reason behind this warning (occasionally, the element is not yet loaded or cannot be located), what is the best course of action to take in response to this error?
Would it suffice to wrap the code that interacts with the element(s) inside an if
condition, similar to the following example:
let divs: HTMLElement | null = document.getElementById("div");
if(divs !== null) {
// carry out operations with divs...
}
Alternatively, should I implement a different approach?
Your advice is greatly appreciated.