[英]How can I solve error - "Object is possibly 'null'"?
在我的 Angular 项目 Typescript 代码中,我收到错误消息:
Object is possibly 'null'
在这条线上:
document.querySelector<HTMLElement>('.highlighted').style.backgroundColor = 'white';
如果我添加?
到上面这样的行:
document.querySelector<HTMLElement>('.highlighted')?.style.backgroundColor = 'white';
然后我收到以下错误:
The left-hand side of an assignment expression may not be an optional property access.ts(2779)
我需要帮助来解决这些错误中的任何一个。
document.querySelector()
可以返回null
。 将其分配给一个变量,然后使用if
语句断言它不是 null,然后再分配给它的一个属性:
const element = document.querySelector<HTMLElement>('.highlighted');
if (element) {
element.style.backgroundColor = 'white';
}
或者,如果您从程序的上下文中知道此查询不会返回null
,则可以使用TypeScript 非空断言( !
) :
document.querySelector<HTMLElement>('.highlighted')!.style.backgroundColor = 'white';
Angular v12 具有严格的类型和 null 检查。 出于这个原因,“。” 派上用场:可以这样使用它:
使用 else 条件进行管理是一个好习惯,分配 '.' 仅当您确定 object 不会为空时。
(代码上下文:尝试使用包含参数-> id 的 url 的路线 map)
一些无知的警长管理员删除了我的最后一个答案,将其标记为“相同”答案。 对不起,但我不欣赏它。 答案与之前的任何答案都不“相同”。
于是再次回答
克服这个问题的最佳方法是使用如下所示的“任何”。 错误将消失
private someVariable: any;
而不是特定类型或 object 等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.