no-for-in-array
Disallow iterating over an array with a for-in loop.
✅
Extending "plugin:@typescript-eslint/recommended-type-checked"
in an ESLint configuration enables this rule.
💭
This rule requires type information to run.
A for-in loop (for (var i in o)
) iterates over the properties of an Object.
While it is legal to use for-in loops with array types, it is not common.
for-in will iterate over the indices of the array as strings, omitting any "holes" in
the array.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-for-in-array": "error"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
declare const array: string[];
for (const i in array) {
console.log(array[i]);
}
for (const i in array) {
console.log(i, array[i]);
}
Open in Playgrounddeclare const array: string[];
for (const value of array) {
console.log(value);
}
for (let i = 0; i < array.length; i += 1) {
console.log(i, array[i]);
}
array.forEach((value, i) => {
console.log(i, value);
})
for (const [i, value] of array.entries()) {
console.log(i, value);
}
Open in PlaygroundOptions
This rule is not configurable.
When Not To Use It
If your project is a rare one that intentionally loops over string indices of arrays, you can turn off this rule. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.