Skip to content

Commit 11e57c5

Browse files
authored
fix(eslint-plugin): [no-unused-vars] handle logical assignment (#7854)
* fix(eslint-plugin): [no-unused-vars] handle logical assignment * refactor
1 parent c426884 commit 11e57c5

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

packages/eslint-plugin/src/util/collectUnusedVariables.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,8 @@ function isExported(variable: TSESLint.Scope.Variable): boolean {
439439
});
440440
}
441441

442+
const LOGICAL_ASSIGNMENT_OPERATORS = new Set(['&&=', '||=', '??=']);
443+
442444
/**
443445
* Determines if the variable is used.
444446
* @param variable The variable to check.
@@ -701,6 +703,7 @@ function isUsedVariable(variable: TSESLint.Scope.Variable): boolean {
701703
ref.isRead() && // in RHS of an assignment for itself. e.g. `a = a + 1`
702704
// self update. e.g. `a += 1`, `a++`
703705
((parent.type === AST_NODE_TYPES.AssignmentExpression &&
706+
!LOGICAL_ASSIGNMENT_OPERATORS.has(parent.operator) &&
704707
grandparent.type === AST_NODE_TYPES.ExpressionStatement &&
705708
parent.left === id) ||
706709
(parent.type === AST_NODE_TYPES.UpdateExpression &&

packages/eslint-plugin/tests/rules/no-unused-vars/no-unused-vars.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1099,6 +1099,18 @@ interface Foo {
10991099
bar: string;
11001100
}
11011101
`,
1102+
`
1103+
let foo = 1;
1104+
foo ??= 2;
1105+
`,
1106+
`
1107+
let foo = 1;
1108+
foo &&= 2;
1109+
`,
1110+
`
1111+
let foo = 1;
1112+
foo ||= 2;
1113+
`,
11021114
],
11031115

11041116
invalid: [
@@ -1844,5 +1856,23 @@ const Foo = 'bar';
18441856
},
18451857
],
18461858
},
1859+
{
1860+
code: `
1861+
let foo = 1;
1862+
foo += 1;
1863+
`,
1864+
errors: [
1865+
{
1866+
messageId: 'unusedVar',
1867+
line: 3,
1868+
column: 1,
1869+
data: {
1870+
varName: 'foo',
1871+
action: 'assigned a value',
1872+
additional: '',
1873+
},
1874+
},
1875+
],
1876+
},
18471877
],
18481878
});

0 commit comments

Comments
 (0)