consistent-type-definitions
Enforce type definitions to consistently use either
interface
ortype
.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic"
可启用此规则。
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
TypeScript 提供了两种定义对象类型的常用方法: interface
和 type
。
英:TypeScript provides two common ways to define an object type: interface
and type
.
// type alias
type T1 = {
a: string;
b: number;
};
// interface keyword
interface T2 {
a: string;
b: number;
}
两者通常非常相似,并且经常可以互换使用。 一致地使用相同的类型声明样式有助于提高代码的可读性。
英:The two are generally very similar, and can often be used interchangeably. Using the same type declaration style consistently helps with code readability.
module.exports = {
"rules": {
"@typescript-eslint/consistent-type-definitions": "error"
}
};
选项
"interface"
(默认): 强制使用interface
进行对象类型定义。"type"
: 强制使用type
进行对象类型定义。
interface
- ❌ 不正确
- ✅ 正确
type T = { x: number };
Open in Playgroundtype T = string;
type Foo = string | {};
interface T {
x: number;
}
Open in Playgroundtype
- ❌ 不正确
- ✅ 正确
interface T {
x: number;
}
Open in Playgroundtype T = { x: number };
Open in Playground何时不使用它
如果你出于风格原因特别想要使用接口或类型字面量,则可以避免此规则。
英:If you specifically want to use an interface or type literal for stylistic reasons, you can avoid this rule.
但是,请记住,不一致的风格可能会损害项目的可读性。 我们建议为此规则选择一个最适合你的项目的选项。
英:However, keep in mind that inconsistent style can harm readability in a project. We recommend picking a single option for this rule that works best for your project.
Record
和 interface
之间还存在难以静态捕捉的细微差别。
例如,如果你的项目是另一个依赖于特定类型定义样式的项目的依赖,则此规则可能会适得其反。
你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
英:There are also subtle differences between Record
and interface
that can be difficult to catch statically.
For example, if your project is a dependency of another project that relies on a specific type definition style, this rule may be counterproductive.
You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.
选项
该规则接受以下选项
type Options = ['interface' | 'type'];
const defaultOptions: Options = ['interface'];