Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(eslint-plugin): [prefer-readonly] add handling for destructuring …
…assignments
  • Loading branch information
a-tarasyuk authored and bradzacher committed Sep 7, 2019
1 parent e01dc5f commit e011e90
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
31 changes: 30 additions & 1 deletion packages/eslint-plugin/src/rules/prefer-readonly.ts
Expand Up @@ -68,7 +68,7 @@ export default util.createRule<Options, MessageIds>({
return;
}

if (ts.isDeleteExpression(parent)) {
if (ts.isDeleteExpression(parent) || isDestructuringAssignment(node)) {
classScope.addVariableModification(node);
return;
}
Expand Down Expand Up @@ -108,6 +108,35 @@ export default util.createRule<Options, MessageIds>({
}
}

function isDestructuringAssignment(
node: ts.PropertyAccessExpression,
): boolean {
let current: ts.Node = node.parent;

while (current) {
const parent = current.parent;

if (
ts.isObjectLiteralExpression(parent) ||
ts.isArrayLiteralExpression(parent) ||
ts.isSpreadAssignment(parent) ||
(ts.isSpreadElement(parent) &&
ts.isArrayLiteralExpression(parent.parent))
) {
current = parent;
} else if (ts.isBinaryExpression(parent)) {
return (
parent.left === current &&
parent.operatorToken.kind === ts.SyntaxKind.EqualsToken
);
} else {
break;
}
}

return false;
}

function isConstructor(node: TSESTree.Node): boolean {
return (
node.type === AST_NODE_TYPES.MethodDefinition &&
Expand Down
48 changes: 48 additions & 0 deletions packages/eslint-plugin/tests/rules/prefer-readonly.test.ts
Expand Up @@ -220,6 +220,54 @@ ruleTester.run('prefer-readonly', rule, {
this['computed'] = 1;
}
}`,
{
code: `
class Foo {
private value: number = 0
bar(newValue: { value: number }) {
({ value: this.value } = newValue);
return this.value;
}
}
`,
},
{
code: `
class Foo {
private value: Record<string, number> = {};
bar(newValue: Record<string, number>) {
({ ...this.value } = newValue);
return this.value;
}
}
`,
},
{
code: `
class Foo {
private value: number[] = []
bar(newValue: number[]) {
[...this.value] = newValue;
return this.value;
}
}
`,
},
{
code: `
class Foo {
private value: number = 0;
bar(newValue: number[]) {
[this.value] = newValue;
return this.value;
}
}
`,
},
],
invalid: [
{
Expand Down

0 comments on commit e011e90

Please sign in to comment.