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)
window.document.getElementById("foobar");
要么返回一个HTMLElement或null
正如您之前可能使用过类似的语句:window.document.getElementById("foobar").value
Typescript 抱怨,该值可能无法访问,您应该在之前明确检查这一点。
为了避免这种情况,您可以执行以下操作:
const element = window.document.getElementById("foobar");
if (element !== null) {
alert(element.value);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37406 次 |
| 最近记录: |