From aadb39f0ff500ee99ea80e9009ab61283ca9c8cd Mon Sep 17 00:00:00 2001 From: Brad Zacher Date: Tue, 1 Dec 2020 13:06:55 -0800 Subject: [PATCH] fix(eslint-plugin): [no-unused-vars] false-positive with class expressions (#2833) Fixes #2831 --- .../src/util/collectUnusedVariables.ts | 26 ++++++++++++------- .../no-unused-vars/no-unused-vars.test.ts | 2 ++ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/packages/eslint-plugin/src/util/collectUnusedVariables.ts b/packages/eslint-plugin/src/util/collectUnusedVariables.ts index bd8ed859b6d..19aaf33565f 100644 --- a/packages/eslint-plugin/src/util/collectUnusedVariables.ts +++ b/packages/eslint-plugin/src/util/collectUnusedVariables.ts @@ -153,6 +153,19 @@ class UnusedVarsVisitor< } } + private visitClass( + node: TSESTree.ClassDeclaration | TSESTree.ClassExpression, + ): void { + // skip a variable of class itself name in the class scope + const scope = this.getScope(node); + for (const variable of scope.variables) { + if (variable.identifiers[0] === scope.block.id) { + this.markVariableAsUsed(variable); + return; + } + } + } + private visitFunction( node: TSESTree.FunctionDeclaration | TSESTree.FunctionExpression, ): void { @@ -201,16 +214,9 @@ class UnusedVarsVisitor< //#region VISITORS // NOTE - This is a simple visitor - meaning it does not support selectors - protected ClassDeclaration(node: TSESTree.ClassDeclaration): void { - // skip a variable of class itself name in the class scope - const scope = this.getScope(node); - for (const variable of scope.variables) { - if (variable.identifiers[0] === scope.block.id) { - this.markVariableAsUsed(variable); - return; - } - } - } + protected ClassDeclaration = this.visitClass; + + protected ClassExpression = this.visitClass; protected FunctionDeclaration = this.visitFunction; diff --git a/packages/eslint-plugin/tests/rules/no-unused-vars/no-unused-vars.test.ts b/packages/eslint-plugin/tests/rules/no-unused-vars/no-unused-vars.test.ts index 9e06ea0dc48..15f19019239 100644 --- a/packages/eslint-plugin/tests/rules/no-unused-vars/no-unused-vars.test.ts +++ b/packages/eslint-plugin/tests/rules/no-unused-vars/no-unused-vars.test.ts @@ -960,6 +960,8 @@ interface _Foo { // ignored by pattern, even though it's only self-referenced options: [{ varsIgnorePattern: '^_' }], }, + // https://github.com/ocavue/typescript-eslint-issue-2831/blob/master/index.ts + 'export const classes = [class C1 {}, class C2 {}, class C3 {}];', ], invalid: [