Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: prefer-destructuring invalid autofix with computed property access #13704

Merged
merged 2 commits into from Sep 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding this also covers the var foo = object['foo']; case, which we don't fix either and for which we already have a test asserting the same.


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