typescript/consistent-type-imports 风格
它的作用
强制统一使用类型导入。
为什么这是个问题?
类型导入使用不一致会使代码更难阅读和理解。
示例
此规则的 错误 代码示例:
ts
import { Foo } from "Foo";
type T = Foo;
type S = import("Foo");此规则的 正确 代码示例:
ts
import type { Foo } from "Foo";使用 "prefer": "type-imports"(默认值)时的示例
错误 代码示例:
ts
import { Foo } from "foo";
let foo: Foo;正确 代码示例:
ts
import type { Foo } from "foo";
let foo: Foo;使用 "prefer": "no-type-imports" 时的示例
错误 代码示例:
ts
import type { Foo } from "foo";
let foo: Foo;正确 代码示例:
ts
import { Foo } from "foo";
let foo: Foo;使用 "fixStyle": "inline-type-imports" 时的示例
在修复类型导入时,此选项将使用内联 type 修饰符:
ts
// 修复前
import { A, B } from "foo";
type T = A;
const b = B;
// 修复后
import { type A, B } from "foo";
type T = A;
const b = B;使用 "disallowTypeAnnotations": false 时的示例
当设置为 false 时,允许在 import() 中使用类型注解:
ts
type T = import("foo").Bar;配置
此规则接受一个配置对象,包含以下属性:
disallowTypeAnnotations
type: boolean
默认值: true
禁止在类型注解中使用 import(),例如 type T = import('foo')
fixStyle
type: "separate-type-imports" | "inline-type-imports"
默认值: "separate-type-imports"
控制自动修复时如何添加类型导入。
"separate-type-imports"
将在 import 关键字后添加 type 保留字,如 import type { A } from '...'
"inline-type-imports"
将内联 type 保留字,如 import { type A } from '...'(仅在 TypeScript 4.5+ 中可用)
prefer
type: "type-imports" | "no-type-imports"
默认值: "type-imports"
控制是否强制使用类型导入或值导入。
"type-imports"
强制要求始终使用 import type Foo from '...',除非被装饰器元数据引用。
"no-type-imports"
强制要求始终使用 import Foo from '...'
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/consistent-type-imports": "error"
}
}bash
oxlint --deny typescript/consistent-type-imports