Skip to content

Commit c618707

Browse files
authored
fix: ignore vars with non-identifier references in no-useless-assignment (#19200)
* feat: check only Identifier's reference in `no-useless-assignment` * review * add test cases * review
1 parent e2bb429 commit c618707

File tree

2 files changed

+76
-1
lines changed

2 files changed

+76
-1
lines changed

lib/rules/no-useless-assignment.js

+9
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,15 @@ module.exports = {
309309
}
310310

311311

312+
if (targetAssignment.variable.references.some(ref => ref.identifier.type !== "Identifier")) {
313+
314+
/**
315+
* Skip checking for a variable that has at least one non-identifier reference.
316+
* It's generated by plugins and cannot be handled reliably in the core rule.
317+
*/
318+
return;
319+
}
320+
312321
const readReferences = targetAssignment.variable.references.filter(reference => reference.isRead());
313322

314323
if (!readReferences.length) {

tests/lib/rules/no-useless-assignment.js

+67-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
const rule = require("../../../lib/rules/no-useless-assignment");
1313
const RuleTester = require("../../../lib/rule-tester/rule-tester");
14+
const { Reference } = require("eslint-scope");
1415

1516
//------------------------------------------------------------------------------
1617
// Tests
@@ -30,6 +31,21 @@ const ruleTester = new RuleTester({
3031
}
3132
};
3233
}
34+
},
35+
jsx: {
36+
create(context) {
37+
const sourceCode = context.sourceCode;
38+
39+
return {
40+
JSXIdentifier(node) {
41+
const scope = sourceCode.getScope(node);
42+
const variable = scope.variables.find(v => v.name === node.name);
43+
44+
variable.references.push(new Reference(node, scope, Reference.READ, null, false, null));
45+
46+
}
47+
};
48+
}
3349
}
3450
}
3551
}
@@ -353,7 +369,57 @@ ruleTester.run("no-useless-assignment", rule, {
353369
} = obj;
354370
console.log(a, b);`,
355371
`let { a, b: {c = a} = {} } = obj;
356-
console.log(c);`
372+
console.log(c);`,
373+
{
374+
code: `/*eslint test/jsx:1*/
375+
function App() {
376+
const A = "";
377+
return <A/>;
378+
}
379+
`,
380+
languageOptions: {
381+
parserOptions: {
382+
ecmaFeatures: {
383+
jsx: true
384+
}
385+
}
386+
}
387+
},
388+
{
389+
code: `/*eslint test/jsx:1*/
390+
function App() {
391+
let A = "";
392+
foo(A);
393+
A = "A";
394+
return <A/>;
395+
}
396+
`,
397+
languageOptions: {
398+
parserOptions: {
399+
ecmaFeatures: {
400+
jsx: true
401+
}
402+
}
403+
}
404+
},
405+
{
406+
code: `/*eslint test/jsx:1*/
407+
function App() {
408+
let A = "a";
409+
A = "b";
410+
A = "c";
411+
foo(A);
412+
return <A/>;
413+
}
414+
`,
415+
languageOptions: {
416+
parserOptions: {
417+
ecmaFeatures: {
418+
jsx: true
419+
}
420+
}
421+
}
422+
}
357423
],
358424
invalid: [
359425
{

0 commit comments

Comments
 (0)