Skip to content
← Back to rules

typescript/prefer-includes Pedantic

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

What it does

.indexOf() !== -1 또는 /regex/.test() 대신 .includes() 사용을 강제합니다.

Why is this bad?

.includes().indexOf() !== -1 검사를 수행하는 것보다 더 읽기 쉽고 표현력이 뛰어납니다. 값의 존재 여부를 확인하려는 의도를 명확히 전달합니다. 또한 간단한 문자열 검색의 경우, 성능과 명확성 측면에서 .includes()가 보통 정규표현식 .test()보다 선호됩니다.

Examples

이 규칙에 위배되는 잘못된 예시:

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");
}

How to use

구성 파일 또는 CLI를 통해 이 규칙을 활성화하려면 다음을 사용하세요:

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

References