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 or mapped type. 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 IndexSignatureInterface {
[key: string]: unknown;
}

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

type MappedType = {
[key in string]: unknown;
};

type RecordType = Record<string, unknown>;

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

¥Using one declaration form consistently improves code readability.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/consistent-indexed-object-style": "error"
}
});

在线运行试试这个规则 ↗

选项

该规则接受以下选项:

type Options = [
/** Which indexed object syntax to prefer. */
| 'index-signature'
/** Which indexed object syntax to prefer. */
| 'record',
];

const defaultOptions: Options = ['record'];

¥Options

  • 'record'(默认):仅允许 Record 类型。

    ¥'record' (default): only allow the Record type.

  • 'index-signature':只允许索引签名。

    ¥'index-signature': only allow index signatures.

'record'

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

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

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

'index-signature'

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

何时不使用它

¥When Not To Use It

此规则对于其认为可变的内容非常严格。如果你不想为索引对象类型保持一致的样式,则可以将其关闭。

¥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.

'## 资源'