forInGuards
Reports for-in loops without an if statement to filter inherited properties.
✅ This rule is included in the ts preset.
Looping over objects with a for-in loop will include properties inherited through the prototype chain.
This can lead to unexpected items being iterated over when the object inherits from a non-standard prototype.
Examples
Section titled “Examples”for (const key in object) { doSomething(key);}for (const key in object) { doSomething(key);}for (const key in object) { if (condition) { doSomething(key); } doSomethingElse(key);}for (const key in object) { if (Object.hasOwn(object, key)) { doSomething(key); }}for (const key in object) { if (!Object.hasOwn(object, key)) { continue; } doSomething(key);}for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { doSomething(key); }}for (const key in object);for (const key in object) {}Options
Section titled “Options”This rule is not configurable.
When Not To Use It
Section titled “When Not To Use It”If you are certain that the objects you iterate over do not have inherited properties from custom prototypes, you might choose to disable this rule.
This is common when iterating over plain objects created with object literals or Object.create(null).
Further Reading
Section titled “Further Reading”Equivalents in Other Linters
Section titled “Equivalents in Other Linters”- Biome:
useGuardForIn - Deno:
guard-for-in - ESLint:
guard-for-in - Oxlint:
eslint/guard-for-in
Made with ❤️🔥 in Boston by
Josh Goldberg and contributors.