Skip to main content

consistent-indexed-object-style

Require or disallow the Record type.

🎨

ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic" 可启用此规则。

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复


TypeScript 支持使用索引签名定义任意对象键。 TypeScript 还有一个名为 Record 的内置类型,用于创建仅定义索引签名的空对象。 例如,以下类型是相等的:

英:TypeScript supports defining arbitrary object keys using an index signature. TypeScript also has a builtin type named Record to create an empty object defining only an index signature. For example, the following types are equal:

interface Foo {
[key: string]: unknown;
}

type Foo = {
[key: string]: unknown;
};

type Foo = Record<string, unknown>;

坚持使用一种声明形式可以持续提高代码的可读性。

英:Keeping to one declaration form consistently improve code readability.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/consistent-indexed-object-style": "error"
}
};
在线运行试试这个规则 ↗

选项

  • "record"(默认): 只允许 Record 类型。
  • "index-signature": 只允许索引签名。

record

interface Foo {
[key: string]: unknown;
}

type Foo = {
[key: string]: unknown;
};
Open in Playground

index-signature

type Foo = Record<string, unknown>;
Open in Playground

何时不使用它

该规则纯粹是用于保持项目一致性的风格规则。 如果你不想为索引对象类型保持一致的样式,则可以将其关闭。

英:This rule is purely a stylistic rule for maintaining consistency in your project. You can turn it off if you don't want to keep a consistent style for indexed object types.

但是,请记住,不一致的风格可能会损害项目的可读性。 我们建议为此规则选择一个最适合你的项目的选项。

英: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.

选项

该规则接受以下选项

type Options = ['index-signature' | 'record'];

const defaultOptions: Options = ['record'];

资源