Skip to content

Commit

Permalink
feat(eslint-plugin): [consistent-type-imports] Add mixed mode option
Browse files Browse the repository at this point in the history
This ads a new mode called "type-imports-mixed" for consistent-type-imports rule which will only trigger, if all imports of an import declaration are type only imports.

References typescript-eslint#2769
  • Loading branch information
olee committed Dec 6, 2020
1 parent ccb6b94 commit 84cc023
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
11 changes: 7 additions & 4 deletions packages/eslint-plugin/src/rules/consistent-type-imports.ts
Expand Up @@ -6,7 +6,7 @@ import {
} from '@typescript-eslint/experimental-utils';
import * as util from '../util';

type Prefer = 'type-imports' | 'no-type-imports';
type Prefer = 'type-imports' | 'no-type-imports' | 'type-imports-mixed';

type Options = [
{
Expand Down Expand Up @@ -67,7 +67,7 @@ export default util.createRule<Options, MessageIds>({
type: 'object',
properties: {
prefer: {
enum: ['type-imports', 'no-type-imports'],
enum: ['type-imports', 'no-type-imports', 'type-imports-mixed'],
},
disallowTypeAnnotations: {
type: 'boolean',
Expand All @@ -94,7 +94,7 @@ export default util.createRule<Options, MessageIds>({
const sourceImportsMap: { [key: string]: SourceImports } = {};

return {
...(prefer === 'type-imports'
...(prefer !== 'no-type-imports'
? {
// prefer type imports
ImportDeclaration(node: TSESTree.ImportDeclaration): void {
Expand Down Expand Up @@ -157,7 +157,10 @@ export default util.createRule<Options, MessageIds>({
}
}

if (typeSpecifiers.length) {
if (
typeSpecifiers.length &&
(prefer === 'type-imports' || valueSpecifiers.length === 0)
) {
sourceImports.reportValueImports.push({
node,
typeSpecifiers,
Expand Down
37 changes: 37 additions & 0 deletions packages/eslint-plugin/tests/rules/consistent-type-imports.test.ts
Expand Up @@ -109,6 +109,23 @@ ruleTester.run('consistent-type-imports', rule, {
`,
options: [{ prefer: 'no-type-imports' }],
},
// type-imports-mixed
{
code: `
import { A, B } from 'foo';
const foo: A = B();
`,
options: [{ prefer: 'type-imports-mixed' }],
},
{
code: `
import type A from 'foo';
import B from 'foo';
let foo: A;
let bar = B;
`,
options: [{ prefer: 'type-imports-mixed' }],
},
// exports
`
import Type from 'foo';
Expand Down Expand Up @@ -1215,5 +1232,25 @@ const a: Default = '';
},
],
},
{
code: `
import { A, B } from 'foo';
let foo: A;
let bar: B;
`,
output: `
import type { A, B } from 'foo';
let foo: A;
let bar: B;
`,
options: [{ prefer: 'type-imports-mixed' }],
errors: [
{
messageId: 'typeOverValue',
line: 2,
column: 1,
},
],
},
],
});

0 comments on commit 84cc023

Please sign in to comment.