Skip to main content

prefer-ts-extras-array-index-of

Prefer arrayIndexOf from ts-extras for direct Array.prototype.indexOf calls.

Targeted pattern scopeโ€‹

The receiver must be a native array, readonly array, or tuple. The rule checks the TypeScript declaration of .indexOf and the types of its arguments.

What this rule reportsโ€‹

A direct .indexOf(search) call, optionally with a numeric or undefined fromIndex. Computed members, optional chains, spreads, and arguments with observable side effects are excluded.

Why this rule existsโ€‹

Use arrayIndexOf to find an item in a readonly tuple using a wider search type.

โŒ Incorrectโ€‹

const statuses = ["idle", "ready", "ready"] as const;
const index = statuses.indexOf("ready");

โœ… Correctโ€‹

import { arrayIndexOf } from "ts-extras";

const statuses = ["idle", "ready", "ready"] as const;
const index = arrayIndexOf(statuses, "ready");

Behavior and migration notesโ€‹

The result is a numeric index, including -1 for a missing item. The helper accepts a wider search type such as unknown when it contains the element type. Pass an existing fromIndex through unchanged to preserve the starting position.

The rule requires type information and a stable ts-extras 2.x or 3.x release. It reports without applying an edit. Review code that reassigns native methods before replacing the call.

Additional examplesโ€‹

โŒ Incorrect โ€” Additional exampleโ€‹

const statuses = ["idle", "ready", "ready"] as const;
const result = statuses.indexOf("ready", 1);

โœ… Correct โ€” Additional exampleโ€‹

import { arrayIndexOf } from "ts-extras";

const statuses = ["idle", "ready", "ready"] as const;
const result = arrayIndexOf(statuses, "ready", 1);

โœ… Correct โ€” Repository-wide usageโ€‹

import { arrayIndexOf } from "ts-extras";

export const searchStatus = (statuses: readonly string[], candidate: unknown) =>
arrayIndexOf(statuses, candidate);

ESLint flat config exampleโ€‹

import parser from "@typescript-eslint/parser";
import typefest from "eslint-plugin-typefest";

export default [
{
files: ["**/*.ts"],
languageOptions: { parser, parserOptions: { projectService: true } },
plugins: { typefest },
rules: { "typefest/prefer-ts-extras-array-index-of": "warn" },
},
];

When not to use itโ€‹

Leave this rule disabled if your project prefers direct native searches.

Package documentationโ€‹

ts-extras package documentation:

arrayIndexOf implementation and overloads

Rule catalog ID: R128

Further readingโ€‹

Adoption resourcesโ€‹