AphrodyBun GitHub

Runtime docs · Linter · Rules

@typescript-eslint/consistent-type-imports

Require import type for imports that are only used as types

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:

bunfig.toml
[lint.rules]
"@typescript-eslint/consistent-type-imports" = "error" # or "warn"

Every option, set to its default:

bunfig.toml
[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

Reported:

import { User } from "./models";

export function greet(user: User) {
  return `Hello, ${user.name}`;
}
import { User, createUser } from "./models";

export const admin: User = createUser("Ada");

Not reported:

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

OptionDefaultWhat 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.
disallowTypeAnnotationstrueAlso report import("./models") in a type.
import type { User } from "./models";

export type Users = User[];
import { User } from "./models";

export type Users = User[];

By default, a type written as import() is reported:

export type Users = import("./models").User[];
export 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) {}
}