Skip to content
← Back to rules

typescript/no-import-type-side-effects 限制

An auto-fix is available for this rule.

它的作用

当导入仅包含带有内联类型限定符的导出项时,强制在顶层使用 import type 限定符。

为什么这是不好的?

--verbatimModuleSyntax 编译器选项会导致 TypeScript 对导入声明进行简单且可预测的转译。具体来说,它会完全移除带有顶层类型限定符的导入声明,并移除任何带有内联类型限定符的导入导出项。

后一种行为在某些情况下会产生一个潜在的意外效果,即在运行时可能会留下一个“副作用”导入:

ts
import { type A, type B } from "mod";

会被转译为

ts
import {} from "mod";
// 等同于
import "mod";

对于极少数需要导入以产生副作用的情况,这可能是期望的行为;但在大多数情况下,你不希望留下不必要的副作用导入。

示例

此规则的错误代码示例:

ts
import { type A } from "mod";
import { type A as AA } from "mod";
import { type A, type B } from "mod";
import { type A as AA, type B as BB } from "mod";

此规则的正确代码示例:

ts
import type { A } from "mod";
import type { A as AA } from "mod";
import type { A, B } from "mod";
import type { A as AA, B as BB } from "mod";

如何使用

通过配置文件或 CLI 启用此规则,可以使用:

json
{
  "rules": {
    "typescript/no-import-type-side-effects": "error"
  }
}
bash
oxlint --deny typescript/no-import-type-side-effects

参考资料