π Disallow dynamic object property existence checks.
πΌπ« This rule is enabled in the β
recommended config. This rule is disabled in the βοΈ unopinionated config.
π‘ This rule is manually fixable by editor suggestions.
Dynamic property access and the in operator check inherited properties too. This can make values like constructor and toString look present even when the object does not define them.
Use Object.hasOwn() when you need to check whether an object has its own property. Prefer Map#has() or Set#has() when the value is really a lookup table.
// β
if (object[key]) {}
// β
if (key in object) {}
// β
if (object[key] === true) {}
// β
if (Object.hasOwn(object, key)) {}// β
const value = object[key];
// β
if ('key' in object) {}
// β
if (object['key']) {}When type information is available and the property value is a known boolean, the access is a value read rather than an existence check, so it's allowed:
declare const object: {a: boolean; b: boolean};
declare const key: 'a' | 'b';
// β
if (object[key]) {}A receiver that is known to be a Map, Set, WeakMap, WeakSet, or string is ignored, since Object.hasOwn() is not the replacement there. Use Map#has() or Set#has() for a collection.