不得使用不必要的條件
禁止在類型始終為真或始終為假時使用條件式。
擴充 「plugin:@typescript-eslint/strict-type-checked"
in an ESLint 組態 啟用此規則。
此規則回報的部分問題可由 --fix
ESLint 命令列選項自動修正.
此規則需要 類型資訊 才能執行。
任何用作條件式的運算式都必須能夠評估為真或假,才會被視為「必要」。反過來說,任何始終評估為真或始終評估為假的運算式(由運算式的類型決定)都會被視為不必要,並會被此規則標記。
會檢查以下運算式
- 傳遞給
&&
、||
和?:
(三元運算子)運算式的引數 if
、for
、while
和do-while
陳述式的條件- 選用式串接運算式的基礎值
module.exports = {
"rules": {
"@typescript-eslint/no-unnecessary-condition": "error"
}
};
在遊樂場中嘗試這條規則 ↗
範例
- ❌ 不正確
- ✅ 正確
function head<T>(items: T[]) {
// items can never be nullable, so this is unnecessary
if (items) {
return items[0].toUpperCase();
}
}
function foo(arg: 'bar' | 'baz') {
// arg is never nullable or empty string, so this is unnecessary
if (arg) {
}
}
function bar<T>(arg: string) {
// arg can never be nullish, so ?. is unnecessary
return arg?.length;
}
// Checks array predicate return types, where possible
[
[1, 2],
[3, 4],
].filter(t => t); // number[] is always truthy
在遊樂場中開啟function head<T>(items: T[]) {
// Necessary, since items.length might be 0
if (items.length) {
return items[0].toUpperCase();
}
}
function foo(arg: string) {
// Necessary, since foo might be ''.
if (arg) {
}
}
function bar(arg?: string | null) {
// Necessary, since arg might be nullish
return arg?.length;
}
[0, 1, 2, 3].filter(t => t); // number can be truthy or falsy
在遊樂場中開啟選項
這條規則接受以下選項
type Options = [
{
/** Whether to ignore constant loop conditions, such as `while (true)`. */
allowConstantLoopConditions?: boolean;
/** Whether to not error when running with a tsconfig that has strictNullChecks turned. */
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;
},
];
const defaultOptions: Options = [
{
allowConstantLoopConditions: false,
allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing: false,
},
];
allowConstantLoopConditions
適用於 { allowConstantLoopConditions: true }
正確程式碼的範例
while (true) {}
for (; true; ) {}
do {} while (true);
在遊樂場中開啟allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing
如果此程式設為 false
,則此規則會對 tsconfig.json
沒有設定 strictNullChecks
編譯器選項 (或 strict
) 為 true
的每個檔案產生錯誤。
沒有 strictNullChecks
,TypeScript 基本會將 undefined
和 null
從類型中移除。這表示當此規則檢查變數的類型時,它無法判斷變數可能是 null
或 undefined
,這在基本上讓此規則毫無用處。
你應該使用 strictNullChecks
來確保程式碼庫中的類型完全安全。
若因某種原因無法開啟 strictNullChecks
,但仍想使用此規則 - 你可以使用此選項來啟用它 - 但請知道此規則的行為在關閉編譯器選項時是未定義的。如果你使用此選項,我們不會接受錯誤回報。
不應使用此規則的情況
如果你的專案並未準確輸入,例如正在轉換成 TypeScript 或容易受到 控制流分析的權衡 影響,則可能難以針對特別是不安全的程式碼區域啟用此規則。你可能會考慮針對特定情況使用 ESLint 停用註解,而非完全停用此規則。
此規則有一個已知的問題,即觸發在函式呼叫中修改的條件 (作為副作用)。這是因為 TypeScript 類型縮小的限制。請詳見 #9998。我們建議在這些情況下使用 類型斷言。
let condition = false as boolean;
const f = () => (condition = true);
f();
if (condition) {
}
相關
- ESLint:no-constant-condition -
no-unnecessary-condition
本質上為no-constant-condition
的加強版,不過需要類型資訊。 - strict-boolean-expressions -
no-unnecessary-condition
的開放式版本。strict-boolean-expressions
強制特定程式碼樣式,而no-unnecessary-condition
則注重正確性。
類型檢查的 Lint 規則比傳統的 Lint 規則更強大,但也需要設定類型檢查 linting。如果在啟用類型檢查規則後遇到效能降低,請參閱 效能問題排除。