no-confusing-non-null-assertion
禁止在容易造成混淆的位置中非空斷言。
🎨
延伸 "plugin:@typescript-eslint/樣式"
在 ESLint 設定 中啟用這項規則。
💡
此規則報告的某些問題可由編輯器 hand fix 建議.
在非空斷言 (!
) 旁邊加上指派或等號檢查 (=
或 ==
或 ===
) 會產生容易造成混淆的程式碼,因為它的外觀類似於不等於檢查 (!=
!==
)。
a! == b; // a non-null assertions(`!`) and an equals test(`==`)
a !== b; // not equals test(`!==`)
a! === b; // a non-null assertions(`!`) and an triple equals test(`===`)
這項規則標記混淆的 !
斷言,並建議移除它們或使用圓括弧 ()
包圍斷言的表達式。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-confusing-non-null-assertion": "error"
}
};
在遊樂場中嘗試這項規則 ↗
範例
- ❌ 錯誤
- ✅ 正確
interface Foo {
bar?: string;
num?: number;
}
const foo: Foo = getFoo();
const isEqualsBar = foo.bar! == 'hello';
const isEqualsNum = 1 + foo.num! == 2;
在遊樂場中開啟interface Foo {
bar?: string;
num?: number;
}
const foo: Foo = getFoo();
const isEqualsBar = foo.bar == 'hello';
const isEqualsNum = (1 + foo.num!) == 2;
在遊樂場中開啟選項
此規則不可配置。
何時不使用它
如果你不在乎這個混淆,那你就不需要此規則。