Skip to content

Latest commit

Β 

History

History
48 lines (34 loc) Β· 1.48 KB

File metadata and controls

48 lines (34 loc) Β· 1.48 KB

no-collection-bracket-access

πŸ“ Disallow accessing Map, Set, WeakMap, and WeakSet entries with bracket notation.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ’‘ This rule is manually fixable by editor suggestions.

Map, Set, WeakMap, and WeakSet do not store their entries as object properties. Using bracket notation on them sets or reads an ordinary object property instead of a collection entry, which is almost always a mistake. Use the instance methods instead:

  • Reading: Map#get()/Map#has(), Set#has()
  • Writing: Map#set(), Set#add()
  • Deleting: Map#delete(), Set#delete()

Detection works for collections created with new Map() (and the other constructors) assigned to a const, or for values whose TypeScript type is known. Accessing a real member (map['size']) or iterating with a Symbol key (map[Symbol.iterator]) is allowed.

Examples

const map = new Map();

// ❌
map['foo'] = 'bar';
// βœ…
map.set('foo', 'bar');

// ❌
const value = map['foo'];
// βœ…
const value = map.get('foo');

// ❌
delete map['foo'];
// βœ…
map.delete('foo');
const set = new Set();

// ❌
if (set['foo']) {}
// βœ…
if (set.has('foo')) {}