Skip to main content

no-confusing-non-null-assertion

Disallow non-null assertion in locations that may be confusing.

🎨

ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic" 可启用此规则。

💡

此规则报告的一些问题可以通过编辑器 建议 手动修复。

在赋值或相等性检查(======)旁边使用非空断言(!)会创建令人困惑的代码,因为它看起来类似于不等性检查(!= !==)。

¥Using a non-null assertion (!) next to an assignment or equality check (= or == or ===) creates code that is confusing as it looks similar to an inequality check (!= !==).

a! == b; // a non-null assertion(`!`) and an equals test(`==`)
a !== b; // not equals test(`!==`)
a! === b; // a non-null assertion(`!`) and a triple equals test(`===`)

在 in 测试(in)或 instanceof 测试(instanceof)旁边使用非空断言(!)会创建令人困惑的代码,因为它可能看起来像运算符被否定,但实际上并非如此。

¥Using a non-null assertion (!) next to an in test (in) or an instanceof test (instanceof) creates code that is confusing since it may look like the operator is negated, but it is actually not.

a! in b; // a non-null assertion(`!`) and an in test(`in`)
a !in b; // also a non-null assertion(`!`) and an in test(`in`)
!(a in b); // a negated in test

a! instanceof b; // a non-null assertion(`!`) and an instanceof test(`instanceof`)
a !instanceof b; // also a non-null assertion(`!`) and an instanceof test(`instanceof`)
!(a instanceof b); // a negated instanceof test

此规则标记令人困惑的 ! 断言,并建议删除它们或将断言表达式封装在 () 括号中。

¥This rule flags confusing ! assertions and suggests either removing them or wrapping the asserted expression in () parenthesis.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-confusing-non-null-assertion": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

interface Foo {
bar?: string;
num?: number;
}

const foo: Foo = getFoo();
const isEqualsBar = foo.bar! == 'hello';
const isEqualsNum = 1 + foo.num! == 2;
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你不关心这种混乱,那么你就不需要这个规则。

¥If you don't care about this confusion, then you will not need this rule.

进一步阅读

¥Further Reading

'## 资源'