Typescript 当我得到“a”时,我到底应该做什么;对象可能为空";打字错误?
在我的Typescript 当我得到“a”时,我到底应该做什么;对象可能为空";打字错误?,typescript,error-handling,null,compiler-options,Typescript,Error Handling,Null,Compiler Options,在我的tsconfig.json文件的compilerOptions对象中,我将strictNullChecks选项设置为true 有时,当我使用诸如getElementById(“…”)或querySelector(“…”)之类的函数时,会出现以下(非致命)错误: TS2531:对象可能为“null” 我知道为什么会出现这个错误(有时元素还没有加载或者找不到),但是当我出现这个错误时,我应该怎么做呢 将使用元素的代码放入if条件中是否合适,如下所示: let divs: HTMLElement
tsconfig.json
文件的compilerOptions
对象中,我将strictNullChecks
选项设置为true
有时,当我使用诸如getElementById(“…”)
或querySelector(“…”)
之类的函数时,会出现以下(非致命)错误:
TS2531:对象可能为“null”
我知道为什么会出现这个错误(有时元素还没有加载或者找不到),但是当我出现这个错误时,我应该怎么做呢
将使用元素的代码放入if
条件中是否合适,如下所示:
let divs: HTMLElement | null = document.getElementById("div");
if(divs !== null) {
// do stuff with divs...
}
还是我应该做点别的
谢谢
将使用元素的代码放在if条件中是否合适
对。正如您所说,有时元素不在那里,因此您会得到null
。检查它是否合适
如果在您知道元素存在的情况下需要使用getElementById
或querySelector
,您可以为自己提供一个helper函数,该函数将抛出而不是返回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;
}
…并在您知道元素将在那里的情况下使用它