Javascript 类型错误:对象可能是';空';。用于window.document的TS2531
第一次将Typescript添加到我的项目中 在一个地方,我使用了Javascript 类型错误:对象可能是';空';。用于window.document的TS2531,javascript,typescript,typescript2.0,Javascript,Typescript,Typescript2.0,第一次将Typescript添加到我的项目中 在一个地方,我使用了window.document.getElementById来访问一些东西。这是一个错误 Type error: Object is possibly 'null'. TS2531 我在网上搜索,但找不到最好的解决方案。窗口不能为空。如何修复此错误? 请提供帮助。window.document.getElementById(“foobar”) 正在返回HTMLElement或null 正如您之前可能使用的类似语句:window
window.document.getElementById
来访问一些东西。这是一个错误
Type error: Object is possibly 'null'. TS2531
我在网上搜索,但找不到最好的解决方案。窗口不能为空。如何修复此错误?
请提供帮助。window.document.getElementById(“foobar”)代码> 正在返回
HTMLElement
或null
正如您之前可能使用的类似语句:window.document.getElementById(“foobar”).value
Typescript正在抱怨,该值可能无法访问,您应该在访问之前明确检查
要避免这种情况,可以执行以下操作:
const element = window.document.getElementById("foobar");
if (element !== null) {
alert(element.value);
}
TS正在执行它的任务,并告诉您
window.document.getElementById(“foobar”)
可能返回null
的内容
如果您完全确定DOM中确实存在#foobar
元素,那么就可以用来显示您的信心代码>操作员
// Notice the "!" at the end of line
const myAbsolutelyNotNullElement = window.document.getElementById("foobar")!
或者,您可以添加运行时可为null的检查以使TS满意
const myMaybeNullElement = window.document.getElementById("foobar")
myMaybeNullElement.nodeName // <- error!
if (myMaybeNullElement === null) {
alert('oops');
} else {
// since you've done the nullable check
// TS won't complain from this point on
myMaybeNullElement.nodeName // <- no error
}
const myMaybeNullElement=window.document.getElementById(“foobar”)
myMaybeNullElement.nodeName/Typescript抱怨在您的情况下执行的window.document.getElementById
的结果对象可以为空
这可以使用tsconfig.json中的标志关闭,我不推荐使用该标志
或者,您可以按照其他答案中的建议进行检查,或者从Typescript 3.7开始使用语法使代码更加简洁:
obj?.doSometething(); //good, will not do something.
obj?.prop = 'plop'; //not good because it does not work with assignments.
加上这个。(?)在数组中,例如:
form.get('description')?.errors
在这里,您必须确保您的window.document.getElementById(“id\u name”)代码>已设置。你可以试试这个
const element = window.document.getElementById("id_name");
if(element){
console.log(element);
}
你确定只有窗口
是空的吗?啊,现在有问题了。这是因为元素可能为空。谢谢谢谢你!TS给出了一个有效的错误。我只是没有意识到这是为了元素而不是窗口..在变量中捕获它对我来说很有用,就像使用!不是一个选项,因为这实际上违背了严格模式的目的。还有严格模式也有“禁止非空断言”规则停止使用!