Skip to content

Commit

Permalink
Fix: prefer-destructuring invalid autofix with computed property acce…
Browse files Browse the repository at this point in the history
…ss (#13704)

* Fix: prefer-destructuring invalid autofix with computed property access

* Clarify --fix in the docs
  • Loading branch information
mdjermanovic committed Sep 26, 2020
1 parent 46c73b1 commit cb44e93
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/rules/prefer-destructuring.md
Expand Up @@ -21,6 +21,8 @@ The rule has a second object with a single key, `enforceForRenamedProperties`, w
- Accessing an object property whose key is an integer will fall under the category `array` destructuring.
- Accessing an array element through a computed index will fall under the category `object` destructuring.

The `--fix` option on the command line fixes only problems reported in variable declarations, and among them only those that fall under the category `object` destructuring. Furthermore, the name of the declared variable has to be the same as the name used for non-computed member access in the initializer. For example, `var foo = object.foo` can be automatically fixed by this rule. Problems that involve computed member access (e.g., `var foo = object[foo]`) or renamed properties (e.g., `var foo = object.bar`) are not automatically fixed.

Examples of **incorrect** code for this rule:

```javascript
Expand Down
2 changes: 2 additions & 0 deletions lib/rules/prefer-destructuring.js
Expand Up @@ -163,6 +163,8 @@ module.exports = {
return node.type === "VariableDeclarator" &&
node.id.type === "Identifier" &&
node.init.type === "MemberExpression" &&
!node.init.computed &&
node.init.property.type === "Identifier" &&
node.id.name === node.init.property.name;
}

Expand Down
10 changes: 10 additions & 0 deletions tests/lib/rules/prefer-destructuring.js
Expand Up @@ -237,6 +237,16 @@ ruleTester.run("prefer-destructuring", rule, {
type: "VariableDeclarator"
}]
},
{
code: "var foo = object[foo];",
output: null,
options: [{ object: true }, { enforceForRenamedProperties: true }],
errors: [{
messageId: "preferDestructuring",
data: { type: "object" },
type: "VariableDeclarator"
}]
},
{
code: "var foo = object['foo'];",
output: null,
Expand Down

0 comments on commit cb44e93

Please sign in to comment.