繁体   English   中英

document.getElementById() 的禁止非空断言 lint 错误

[英]Forbidden non-null assertion lint error for document.getElementById()

我正在使用 TypeScript,我有以下定义:

const contentElement = document.getElementById("contentId")!;

我确定相关元素在带有contendId的 HTML 文件中定义。

我运行了 eslint,但出现以下错误:

Forbidden non-null assertion.

那么......处理这种情况的正确方法是什么? 倾向于简单地添加抑制警告,因为其他选项只会增加复杂性。 但也许我在这里忽略了一个简单的解决方案,除了添加:

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion

Forbidden non-null assertion. 只是一个 lint 警告/错误,因为您的值可以为空。 如果您确定该值,则可以将其转换为预期的类型,如下所示

const contentElement = document.getElementById("contentId") as HTMLElement

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM