for...in walks the keys of an object, not the items of an array. Over an array, the keys are the indexes as strings, so i + 1 gives "01" and not 1. The loop also skips holes, and it visits any other enumerable property that the array or its prototype has.
The rule reports arrays, tuples and array-like objects such as a NodeList. That covers any type with numeric indexes and a numeric length.
bun lint --type-aware turns this rule on in TypeScript files.
Configure
Off by default. This rule needs types, so turning it on makes bun lint type check your code first.
bunfig.toml
[lint.rules]
"@typescript-eslint/no-for-in-array" = "error" # or "warn"
Examples
Reported:
const prices = [5, 10, 20];
for (const i in prices) {
console.log(i + 1); // "01", "11", "21"
}
const links = document.querySelectorAll("a");
for (const key in links) {
console.log(key); // "0", "1", and also "length", "item", "forEach", ...
}
Not reported:
const prices = [5, 10, 20];
for (const price of prices) {
console.log(price);
}
for (const [i, price] of prices.entries()) {
console.log(i + 1, price);
}
const stock = { apples: 3, pears: 7 };
for (const name in stock) {
console.log(name);
}