@typescript-eslint/no-for-in-array
Disallow for...in over an array
needs types
Also called typescript-eslint/no-for-in-array, typescript/no-for-in-array
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#
example.ts1 problem
const prices = [5, 10, 20];
for (const i in prices)For-in loops over arrays skips holes, returns indices as strings, and may visit the prototype chain or other enumerable properties. Use a more robust iteration method such as for-of or array.forEach instead. {
console.log(i + 1); // "01", "11", "21"
}example.ts1 problem
const links = document.querySelectorAll("a");
for (const key in links)For-in loops over arrays skips holes, returns indices as strings, and may visit the prototype chain or other enumerable properties. Use a more robust iteration method such as for-of or array.forEach instead. {
console.log(key); // "0", "1", and also "length", "item", "forEach", ...
}example.tsNo problems
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);
}example.tsNo problems
const stock = { apples: 3, pears: 7 };
for (const name in stock) {
console.log(name);
}