prefer-includes
對
indexOf
方法強制使用includes
方法。
🔒
延伸 「plugin:@typescript-eslint/strict-type-checked」"
在 ESLint 組態 中啟用這個規則。
🔧
其中一些由這個規則通報的問題,可透過 --fix
ESLint 指令列選項自動修正.
💭
這個規則需要 型別資訊 才能執行。
在 ES2015 之前,Array#indexOf
和 String#indexOf
對比 -1
是檢查值是否分別存在於陣列或字串中的標準方法。現在有更易於閱讀和撰寫的替代方法:ES2015 加入 String#includes
,ES2016 加入 Array#includes
。
這個規則通報 .indexOf
呼叫可替換為 .includes
的情形。此外,這個規則也通報使用相對簡單的正規表達式進行測試時應使用 String#includes
。
此規則會通報任何具有
includes
方法且參數與該方法相同的indexOf
方法呼叫的接收物件。相符的類型包括:String
、Array
、ReadonlyArray
和已建構陣列。
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-includes": "error"
}
};
在操場上嘗試這條規則 ↗
範例
- ❌ 不正確
- ✅ 正確
const str: string;
const array: any[];
const readonlyArray: ReadonlyArray<any>;
const typedArray: UInt8Array;
const maybe: string;
const userDefined: {
indexOf(x: any): number;
includes(x: any): boolean;
};
str.indexOf(value) !== -1;
array.indexOf(value) !== -1;
readonlyArray.indexOf(value) === -1;
typedArray.indexOf(value) > -1;
maybe?.indexOf('') !== -1;
userDefined.indexOf(value) >= 0;
/example/.test(str);
在操場上開啟const str: string;
const array: any[];
const readonlyArray: ReadonlyArray<any>;
const typedArray: UInt8Array;
const maybe: string;
const userDefined: {
indexOf(x: any): number;
includes(x: any): boolean;
};
str.includes(value);
array.includes(value);
!readonlyArray.includes(value);
typedArray.includes(value);
maybe?.includes('');
userDefined.includes(value);
str.includes('example');
// The two methods have different parameters.
declare const mismatchExample: {
indexOf(x: unknown, fromIndex?: number): number;
includes(x: unknown): boolean;
};
mismatchExample.indexOf(value) >= 0;
在操場上開啟選項
此規則無法設定。
何時不使用
類型檢查的 linter 規則強於傳統 linter 規則,但亦需要設定 類型檢查 linting。如果你啟用類型檢查的規則後,效能出現下降,請參閱 效能疑難排解。