no-non-null-asserted-nullish-coalescing
禁止在 nullish 合併運算式的左側運算元中使用非 null 斷言。
🔒
擴充 "plugin:@typescript-eslint/strict"
in an ESLint configuration enables this rule.
💡
此規則所報告的有些問題可透過編輯器手動修正 建議.
??
nullish 合併時期運算元可以在處理 null
或 undefined
時提供預設值。在 nullish 合併運算式的左側運算元中使用 !
非 null 斷言型別運算元是多餘的,而且可能是程式設計人員錯誤或混淆這兩個運算元的跡象。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-non-null-asserted-nullish-coalescing": "error"
}
};
在遊樂場中嘗試此規則 ↗
範例
- ❌ 不正確
- ✅ 正確
foo! ?? bar;
foo.bazz! ?? bar;
foo!.bazz! ?? bar;
foo()! ?? bar;
let x!: string;
x! ?? '';
let x: string;
x = foo();
x! ?? '';
在遊樂場中開啟foo ?? bar;
foo ?? bar!;
foo!.bazz ?? bar;
foo!.bazz ?? bar!;
foo() ?? bar;
// This is considered correct code because there's no way for the user to satisfy it.
let x: string;
x! ?? '';
在遊樂場中開啟選項
此規則無法設定。
不適於使用情況
如果專案類型尚未完整說明特定值可能是可為 Null,例如在轉移至 strictNullChecks
時,這項規則可能會建立許多錯誤回報。你可以考慮在那些特殊情況下使用 ESLint 禁用註解,而不是完全停用這項規則。