类型错误:对象可能为“空”。TS2531 用于 window.document

gho*_*der 17 javascript typescript typescript2.0

第一次将 Typescript 添加到我的项目中。

在一个地方,我曾经window.document.getElementById访问过一些东西。它给出了这个错误。

Type error: Object is possibly 'null'.  TS2531
Run Code Online (Sandbox Code Playgroud)

我在网上搜索,但无法找到最佳解决方案。窗口永远不能为空。我该如何解决这个错误?请帮忙。

hac*_*ape 34

TS 正在做它的工作,并告诉您可以window.document.getElementById("foobar")返回null.

如果您绝对确定该#foobar元素确实存在于您的 DOM 中,您可以向 TS 展示您对!操作符的信心。

// Notice the "!" at the end of line
const myAbsolutelyNotNullElement = window.document.getElementById("foobar")!
Run Code Online (Sandbox Code Playgroud)

或者,你可以添加一个运行时可为空的检查,让 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
}
Run Code Online (Sandbox Code Playgroud)


r3d*_*0rm 8

window.document.getElementById("foobar");

要么返回一个HTMLElementnull

正如您之前可能使用过类似的语句:window.document.getElementById("foobar").value

Typescript 抱怨,该值可能无法访问,您应该在之前明确检查这一点。

为了避免这种情况,您可以执行以下操作:

const element = window.document.getElementById("foobar");

if (element !== null) {
    alert(element.value);
}
Run Code Online (Sandbox Code Playgroud)

  • 将其捕获在变量中对我有用,就像使用 ! 不是一个选项,因为这确实违背了严格模式的目的。另外严格模式还有“禁止非空断言”规则来停止使用! (2认同)