Skip to content

Latest commit

Β 

History

History
53 lines (35 loc) Β· 1.84 KB

no-computed-property-existence-check.md

File metadata and controls

53 lines (35 loc) Β· 1.84 KB

no-computed-property-existence-check

πŸ“ 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.

Examples

// ❌
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.