|
| 1 | +# Enforces consistent usage of type imports (`consistent-type-imports`) |
| 2 | + |
| 3 | +TypeScript 3.8 added support for type-only imports. |
| 4 | +Type-only imports allow you to specify that an import can only be used in a type location, allowing certain optimizations within compilers. |
| 5 | + |
| 6 | +## Rule Details |
| 7 | + |
| 8 | +This rule aims to standardize the use of type imports style across the codebase. |
| 9 | + |
| 10 | +## Options |
| 11 | + |
| 12 | +```ts |
| 13 | +type Options = { |
| 14 | + prefer: 'type-imports' | 'no-type-imports'; |
| 15 | + disallowTypeAnnotations: boolean; |
| 16 | +}; |
| 17 | + |
| 18 | +const defaultOptions: Options = { |
| 19 | + prefer: 'type-imports', |
| 20 | + disallowTypeAnnotations: true, |
| 21 | +}; |
| 22 | +``` |
| 23 | + |
| 24 | +### `prefer` |
| 25 | + |
| 26 | +This option defines the expected import kind for type-only imports. Valid values for `prefer` are: |
| 27 | + |
| 28 | +- `type-imports` will enforce that you always use `import type Foo from '...'`. It is default. |
| 29 | +- `no-type-imports` will enforce that you always use `import Foo from '...'`. |
| 30 | + |
| 31 | +Examples of **correct** code with `{prefer: 'type-imports'}`, and **incorrect** code with `{prefer: 'no-type-imports'}`. |
| 32 | + |
| 33 | +```ts |
| 34 | +import type { Foo } from 'Foo'; |
| 35 | +import type Bar from 'Bar'; |
| 36 | +type T = Foo; |
| 37 | +const x: Bar = 1; |
| 38 | +``` |
| 39 | + |
| 40 | +Examples of **incorrect** code with `{prefer: 'type-imports'}`, and **correct** code with `{prefer: 'no-type-imports'}`. |
| 41 | + |
| 42 | +```ts |
| 43 | +import { Foo } from 'Foo'; |
| 44 | +import Bar from 'Bar'; |
| 45 | +type T = Foo; |
| 46 | +const x: Bar = 1; |
| 47 | +``` |
| 48 | + |
| 49 | +### `disallowTypeAnnotations` |
| 50 | + |
| 51 | +If `true`, type imports in type annotations (`import()`) is not allowed. |
| 52 | +Default is `true`. |
| 53 | + |
| 54 | +Examples of **incorrect** code with `{disallowTypeAnnotations: true}`. |
| 55 | + |
| 56 | +```ts |
| 57 | +type T = import('Foo').Foo; |
| 58 | +const x: import('Bar') = 1; |
| 59 | +``` |
| 60 | + |
| 61 | +## When Not To Use It |
| 62 | + |
| 63 | +- If you are not using TypeScript 3.8 (or greater), then you will not be able to use this rule, as type-only imports are not allowed. |
| 64 | +- If you specifically want to use both import kinds for stylistic reasons, you can disable this rule. |
0 commit comments