1 | # `consistent-type-imports`
|
2 |
|
3 | Enforces consistent usage of type imports.
|
4 |
|
5 | TypeScript 3.8 added support for type-only imports.
|
6 | Type-only imports allow you to specify that an import can only be used in a type location, allowing certain optimizations within compilers.
|
7 |
|
8 | ## Rule Details
|
9 |
|
10 | This rule aims to standardize the use of type imports style across the codebase.
|
11 |
|
12 | ## Options
|
13 |
|
14 | ```ts
|
15 | type Options = {
|
16 | prefer: 'type-imports' | 'no-type-imports';
|
17 | disallowTypeAnnotations: boolean;
|
18 | };
|
19 |
|
20 | const defaultOptions: Options = {
|
21 | prefer: 'type-imports',
|
22 | disallowTypeAnnotations: true,
|
23 | };
|
24 | ```
|
25 |
|
26 | ### `prefer`
|
27 |
|
28 | This option defines the expected import kind for type-only imports. Valid values for `prefer` are:
|
29 |
|
30 | - `type-imports` will enforce that you always use `import type Foo from '...'` except referenced by metadata of decorators. It is default.
|
31 | - `no-type-imports` will enforce that you always use `import Foo from '...'`.
|
32 |
|
33 | Examples of **correct** code with `{prefer: 'type-imports'}`, and **incorrect** code with `{prefer: 'no-type-imports'}`.
|
34 |
|
35 | ```ts
|
36 | import type { Foo } from 'Foo';
|
37 | import type Bar from 'Bar';
|
38 | type T = Foo;
|
39 | const x: Bar = 1;
|
40 | ```
|
41 |
|
42 | Examples of **incorrect** code with `{prefer: 'type-imports'}`, and **correct** code with `{prefer: 'no-type-imports'}`.
|
43 |
|
44 | ```ts
|
45 | import { Foo } from 'Foo';
|
46 | import Bar from 'Bar';
|
47 | type T = Foo;
|
48 | const x: Bar = 1;
|
49 | ```
|
50 |
|
51 | ### `disallowTypeAnnotations`
|
52 |
|
53 | If `true`, type imports in type annotations (`import()`) is not allowed.
|
54 | Default is `true`.
|
55 |
|
56 | Examples of **incorrect** code with `{disallowTypeAnnotations: true}`.
|
57 |
|
58 | ```ts
|
59 | type T = import('Foo').Foo;
|
60 | const x: import('Bar') = 1;
|
61 | ```
|
62 |
|
63 | ## When Not To Use It
|
64 |
|
65 | - 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.
|
66 | - If you specifically want to use both import kinds for stylistic reasons, you can disable this rule.
|
67 |
|
68 | ## Attributes
|
69 |
|
70 | - Configs:
|
71 | - [ ] ✅ Recommended
|
72 | - [ ] 🔒 Strict
|
73 | - [x] 🔧 Fixable
|
74 | - [ ] 💭 Requires type information
|