Skip to content
← Back to rules

typescript/prefer-includes 細かい

💭 This rule requires type information.
🛠️ An auto-fix is available for this rule.

何をするか

.includes() を使用して .indexOf() !== -1/regex/.test() の使用を禁止します。

なぜ悪いのか

.includes().indexOf() !== -1 をチェックするよりも読みやすく、意図が明確です。 値の存在を確認することという意図を明確に伝えます。 また、単純な文字列検索の場合、.includes() はパフォーマンスと明確さの観点から、 正規表現の .test() に対して好まれることが多いです。

このルールに対する誤りなコードの例:

ts
// indexOf の使用
const str = "hello world";
if (str.indexOf("world") !== -1) {
  console.log("found");
}

if (str.indexOf("world") != -1) {
  console.log("found");
}

if (str.indexOf("world") > -1) {
  console.log("found");
}

// 単純な文字列に対して正規表現の test を使用
if (/world/.test(str)) {
  console.log("found");
}

// 配列
const arr = [1, 2, 3];
if (arr.indexOf(2) !== -1) {
  console.log("found");
}

このルールに対する正しいコードの例:

ts
// 文字列に対して includes を使用
const str = "hello world";
if (str.includes("world")) {
  console.log("found");
}

// 配列に対して includes を使用
const arr = [1, 2, 3];
if (arr.includes(2)) {
  console.log("found");
}

// 複雑な正規表現パターンは許可される
if (/wo+rld/.test(str)) {
  console.log("found");
}

// フラグ付き正規表現
if (/world/i.test(str)) {
  console.log("found");
}

使い方

設定ファイルまたは CLI でこのルールを有効化するには、次のようにします:

json
{
  "rules": {
    "typescript/prefer-includes": "error"
  }
}
bash
oxlint --type-aware --deny typescript/prefer-includes

参照