typescript - 当TypeScript中出现 “Object is possibly null”错误时,我该怎么办?

标签 typescript error-handling null compiler-options

在我的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。检查是否合适。

如果您需要在知道元素存在的情况下使用getElementByIdquerySelector,则可以给自己一个抛出而不是返回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/

相关文章:

javascript - 获取自身内部的类函数名

node.js - 调用错误优先功能Node JS

postgresql - 如何在属性不为 NULL 的 PostgreSQL 表中进行选择?

json - 使用 Angular http 请求 json 文件时出现 404

angular - 如何在 AngularFire/TypeScript 中访问 FirebaseError 的 "code"属性?

Angular6:尽管绑定(bind),但 View 未更新数据更改

swift - 线程1 : Exception: “attempt to insert row 1 into section 1, but there are only 1 sections after the update”

mysql - 如何将非数字值转换为空白以用于 case 语句?

sql - not in 和 in with null 值之间的区别

php - 如何使用 php sprintf append 正值 "+"但忽略空值