一致类型定义
强制类型定义始终使用
interface或type。
🎨
在 "plugin:@typescript-eslint/stylistic" 中扩展 ESLint 配置 可以启用此规则。
🔧
此规则报告的一些问题可以通过 --fix ESLint 命令行选项 自动修复。
TypeScript 提供两种常见的定义对象类型的方式:interface 和 type。
// type alias
type T1 = {
  a: string;
  b: number;
};
// interface keyword
interface T2 {
  a: string;
  b: number;
}
两者通常非常相似,并且可以互换使用。始终使用相同的类型声明风格有助于提高代码可读性。
.eslintrc.cjs
module.exports = {
  "rules": {
    "@typescript-eslint/consistent-type-definitions": "error"
  }
};
在游乐场中尝试此规则 ↗
选项
此规则接受以下选项
type Options = ['interface' | 'type'];
const defaultOptions: Options = ['interface'];
- "interface"(默认):强制使用- interface来定义对象类型。
- "type":强制使用- type来定义对象类型。
interface
- ❌ 错误
- ✅ 正确
type
何时不使用它
如果您出于风格原因特别想使用接口或类型字面量,可以避免使用此规则。
但是,请记住,不一致的风格会损害项目的可读性。我们建议为该规则选择一个最适合您项目的选项。
Record 和 interface 之间也存在一些细微的差异,这些差异可能难以静态地捕获。例如,如果您的项目是另一个项目的依赖项,而另一个项目依赖于特定的类型定义风格,那么此规则可能适得其反。您可能考虑使用 ESLint 禁用注释 来处理这些特定情况,而不是完全禁用此规则。