第一次将Typescript添加到我的项目中。
在一个地方,我使用window.document.getElementById
访问的东西。它给出了这个错误。
Type error: Object is possibly 'null'. TS2531
我在网上搜索但是无法找到最佳解决方案。窗口不能为空。我该如何解决这个错误?请帮忙。
TS正在做它的工作并且告诉你window.document.getElementById("foobar")
可能会返回null
。
如果您完全确定您的DOM中存在#foobar
元素,那么您可以使用!
运算符向TS显示您的信心。
// Notice the "!" at the end of line
const myAbsolutelyNotNullElement = window.document.getElementById("foobar")!
或者,您可以添加运行时可空检查以使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
}
window.document.getElementById("foobar");
要么返回HTMLElement
或null
正如您之前使用的类似声明:window.document.getElementById("foobar").value
Typescript抱怨,该值可能无法访问,您应该在之前明确检查。
为避免这种情况,您可以执行以下操作:
const element = window.document.getElementById("foobar");
if (element !== null) {
alert(element.value);
}