prefer-dot-notation

January 10, 2021 ยท View on GitHub

:mag: requires type information :wrench: fixable

Enforces the use of obj.foo instead of obj['foo'] where possible.

Rationale

Property access (dot notation) for statically known properties is easier to read and write. TypeScript has stricter checks for property access. Minifiers can mangle names of properties more efficiently when they are only accessed using dot notation.

This rule excludes cases where using dot notation would cause a compile error, e.g. accessing a private property outside of the class. These cases are handled by no-restricted-property-access.

Examples

:thumbsdown: Examples of incorrect code

declare let obj: Record<string, string>;

obj['prop'];
obj['foo_bar'];

1['toString']();

:thumbsup: Examples of correct code

declare let obj: Record<string, string>;

obj.prop;
obj.foo_bar;

(1).toString();
1..toString(); // double dot is intentional to avoid parsing ambiguity
1.0.toString();

// dynamic element access
obj['prop' + Math.random()];
for (const key in obj) {
  console.log(obj[key]);
}

// names that are not allowed as property access, list is not exhaustive
obj[0];
obj['0']
obj['.'];
obj[''];
obj[','];
obj['a-b'];

Further Reading