Skip to content

Commit 6a9674d

Browse files
authored
fix(eslint-plugin): [no-unused-vars] ignore imports used only as types (#9694)
* fix(eslint-plugin): [no-unused-vars] ignore imports used only as types * chore(eslint-plugin): [no-unused-vars] avoid extra calculation before continue
1 parent c3f9dcd commit 6a9674d

File tree

2 files changed

+23
-25
lines changed

2 files changed

+23
-25
lines changed

‎packages/eslint-plugin/src/rules/no-unused-vars.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -579,6 +579,19 @@ export default createRule<Options, MessageIds>({
579579
for (const unusedVar of unusedVars) {
580580
// Report the first declaration.
581581
if (unusedVar.defs.length > 0) {
582+
const usedOnlyAsType = unusedVar.references.some(ref =>
583+
referenceContainsTypeQuery(ref.identifier),
584+
);
585+
586+
const isImportUsedOnlyAsType =
587+
usedOnlyAsType &&
588+
unusedVar.defs.some(
589+
def => def.type === DefinitionType.ImportBinding,
590+
);
591+
if (isImportUsedOnlyAsType) {
592+
continue;
593+
}
594+
582595
const writeReferences = unusedVar.references.filter(
583596
ref =>
584597
ref.isWrite() &&
@@ -589,10 +602,6 @@ export default createRule<Options, MessageIds>({
589602
? writeReferences[writeReferences.length - 1].identifier
590603
: unusedVar.identifiers[0];
591604

592-
const usedOnlyAsType = unusedVar.references.some(ref =>
593-
referenceContainsTypeQuery(ref.identifier),
594-
);
595-
596605
const messageId = usedOnlyAsType ? 'usedOnlyAsType' : 'unusedVar';
597606

598607
const { start } = id.loc;

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

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1173,6 +1173,16 @@ export type Foo = typeof foo;
11731173
11741174
export const bar = (): Foo => foo;
11751175
`,
1176+
`
1177+
import { SomeType } from 'foo';
1178+
1179+
export const value = 1234 as typeof SomeType;
1180+
`,
1181+
`
1182+
import { foo } from 'foo';
1183+
1184+
export type Bar = typeof foo;
1185+
`,
11761186
],
11771187

11781188
invalid: [
@@ -2256,26 +2266,5 @@ export const x = _Foo;
22562266
},
22572267
],
22582268
},
2259-
{
2260-
code: `
2261-
import { foo } from 'foo';
2262-
2263-
export type Bar = typeof foo;
2264-
`,
2265-
errors: [
2266-
{
2267-
messageId: 'usedOnlyAsType',
2268-
data: {
2269-
varName: 'foo',
2270-
action: 'defined',
2271-
additional: '',
2272-
},
2273-
line: 2,
2274-
column: 18,
2275-
endLine: 2,
2276-
endColumn: 21,
2277-
},
2278-
],
2279-
},
22802269
],
22812270
});

0 commit comments

Comments
 (0)