在我的compilerOptions
文件的tsconfig.json
对象中,我将strictNullChecks
选项设置为true
。
有时,当我使用getElementById("...")
或querySelector("...")
之类的函数时,会出现以下(非致命)错误:
TS2531: Object is possibly 'null'
我知道为什么我收到此错误(有时元素尚未加载或找不到),但是当我收到此错误时我该怎么办?
将使用元素的代码放在
if
条件内是否合适,例如:let divs: HTMLElement | null = document.getElementById("div");
if(divs !== null) {
// do stuff with divs...
}
还是我应该做其他事情?
谢谢。
最佳答案
Would it be appropriate to just put the code that used the element(s) inside an if condition
是。如您所说,有时元素不存在,所以您得到
null
。检查是否合适。如果您需要在知道元素存在的情况下使用
getElementById
或querySelector
,则可以给自己一个抛出而不是返回null
的辅助函数:function getGuaranteed(id: string): HTMLElement {
const el = document.getElementById(id);
if (el == null) {
throw new Error("Element #" + id + " not found.");
}
return el as HTMLElement;
}
...并在您知道该元素将存在的情况下使用它。
关于typescript - 当TypeScript中出现 “Object is possibly null”错误时,我该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55741478/