Skip to content
← Back to rules

typescript/no-non-null-asserted-optional-chain 正确性

This rule is turned on by default.
An auto-fix is available for this rule.

它做了什么

禁止在可选链表达式之后使用非空断言。

为什么这是不好的?

根据设计,可选链表达式(?.)在访问的对象为 nullundefined 时,会返回 undefined 作为表达式的值,而不是抛出错误。使用非空断言(!)来断言可选链表达式的返回结果是自相矛盾且很可能错误的,因为它表明代码同时期望值可能是 nullundefined,又同时认为它不可能为空。

在大多数情况下,要么:

  1. 该对象并非可空的,根本不需要使用 ?. 进行属性查找;
  2. 非空断言是错误的,会引入类型安全漏洞。

示例

此规则的错误代码示例:

ts
foo?.bar!;
foo?.bar()!;

此规则的正确代码示例:

ts
foo?.bar;
foo.bar!;

如何使用

要通过配置文件或命令行启用此规则,可以使用:

json
{
  "rules": {
    "typescript/no-non-null-asserted-optional-chain": "error"
  }
}
bash
oxlint --deny typescript/no-non-null-asserted-optional-chain

参考资料