@typescript-eslint/consistent-type-imports
Require import type for imports that are only used as types
Also called typescript-eslint/consistent-type-imports, typescript/consistent-type-imports
import type tells the reader, and every tool that compiles one file at a time, that the import is gone at runtime. A plain import of something that's only used as a type leaves that open. The module may or may not be loaded for its side effects, depending on the compiler and its settings.
--fix adds the type keyword, and splits the import if it also brings in values.
Configure#
Off by default. To turn it on:
[lint.rules]
"@typescript-eslint/consistent-type-imports" = "error" # or "warn"Every option, set to its default:
[lint.rules]
"@typescript-eslint/consistent-type-imports" = ["error", {
prefer = "type-imports", # "type-imports" or "no-type-imports"
# "separate-type-imports" or "inline-type-imports"
fixStyle = "separate-type-imports",
disallowTypeAnnotations = true,
}]Examples#
import { User } from "./models";All imports in the declaration are only used as types. Use import type.
export function greet(user: User) {
return `Hello, ${user.name}`;
}import { User, createUser } from "./models";Imports User are only used as type.
export const admin: User = createUser("Ada");import type { User } from "./models";
import { createUser } from "./models";
export const admin: User = createUser("Ada");import { type User, createUser } from "./models";
export const admin: User = createUser("Ada");Options#
| Option | Default | What it does |
|---|---|---|
prefer | "type-imports" | "type-imports" requires import type. "no-type-imports" reports it. |
fixStyle | "separate-type-imports" | What --fix writes: import type { User }, or with "inline-type-imports", import { type User }. Both forms are accepted in your code with either value. |
disallowTypeAnnotations | true | Also report import("./models") in a type. |
{ "prefer": "no-type-imports" }1 problemimport type { User } from "./models";Use an import instead of an import type.
export type Users = User[];{ "prefer": "no-type-imports" }No problemsimport { User } from "./models";
export type Users = User[];By default, a type written as import() is reported:
export type Users = import("./models").Userimport() type annotations are forbidden.[];{ "disallowTypeAnnotations": false }No problemsexport type Users = import("./models").User[];When not to use it#
TypeScript's verbatimModuleSyntax option makes a missing import type a compile error. If it's on, you only need this rule for its fix.
With experimentalDecorators and emitDecoratorMetadata both on, TypeScript needs some imported types at runtime, and import type removes them. The rule leaves the imports alone in a file that has a decorator. With --type-aware it reads both settings from your tsconfig.json, and checks such a file too if one of them is off.
import { Database } from "./database";
@Injectable()
export class Users {
constructor(private database: Database) {}
}