Urara-Blog/node_modules/.pnpm-store/v3/files/cf/7de7c1d835e6cfd0c049c99ff4cfd020111ea61208389f6704acaadd290601eb626aef75e488d81bc0b5dba7410e53e11d9661c1e9b75021a80e4699d3a21a
2022-08-14 01:14:53 +08:00

92 lines
2.3 KiB
Text

---
description: 'Enforce `includes` method over `indexOf` method.'
---
> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/prefer-includes** for documentation.
Until ES5, we were using `String#indexOf` method to check whether a string contains an arbitrary substring or not.
Until ES2015, we were using `Array#indexOf` method to check whether an array contains an arbitrary value or not.
ES2015 has added `String#includes` and ES2016 has added `Array#includes`.
It makes code more understandable if we use those `includes` methods for the purpose.
## Rule Details
This rule is aimed at suggesting `includes` method if `indexOf` method was used to check whether an object contains an arbitrary value or not.
If the receiver object of the `indexOf` method call has `includes` method and the two methods have the same parameters, this rule does suggestion.
There are such types: `String`, `Array`, `ReadonlyArray`, and typed arrays.
Additionally, this rule reports the tests of simple regular expressions in favor of `String#includes`.
Examples of code for this rule:
<!--tabs-->
### ❌ Incorrect
```ts
let str: string;
let array: any[];
let readonlyArray: ReadonlyArray<any>;
let typedArray: UInt8Array;
let maybe: string;
let 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;
// simple RegExp test
/foo/.test(str);
```
### ✅ Correct
```ts
let array: any[];
let readonlyArray: ReadonlyArray<any>;
let typedArray: UInt8Array;
let userDefined: {
indexOf(x: any): number;
includes(x: any): boolean;
};
let mismatchExample: {
indexOf(x: any, fromIndex?: number): number;
includes(x: any): boolean;
};
str.includes(value);
array.includes(value);
readonlyArray.includes(value);
typedArray.includes(value);
userDefined.includes(value);
// the two methods have different parameters.
mismatchExample.indexOf(value) >= 0;
```
## Options
```jsonc
// .eslintrc.json
{
"rules": {
"@typescript-eslint/prefer-includes": "warn"
}
}
```
This rule is not configurable.
## When Not To Use It
If you don't want to suggest `includes`, you can safely turn this rule off.