Skip to content
← Back to rules

typescript/consistent-indexed-object-style 风格

🛠️ An auto-fix is available for this rule for some violations.

它的作用

在要求使用 Record 类型或索引签名类型之间进行选择。

这两种类型是等价的,该规则强制统一采用其中一种风格:

ts
type Foo = Record<string, unknown>;

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

为什么这是不好的?

对于索引对象类型的风格不一致会损害项目的可读性。

示例

此规则在 consistent-indexed-object-style: ["error", "record"](默认值)下的 错误 代码示例:

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

此规则在 consistent-indexed-object-style: ["error", "record"](默认值)下的 正确 代码示例:

ts
type Foo = Record<string, unknown>;

此规则在 consistent-indexed-object-style: ["error", "index-signature"] 下的 错误 代码示例:

ts
type Foo = Record<string, unknown>;

此规则在 consistent-indexed-object-style: ["error", "index-signature"] 下的 正确 代码示例:

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

配置

此规则接受以下字符串值之一:

"record"

设置为 record 时,强制使用 Record 来表示索引对象类型,例如 Record<string, unknown>

"index-signature"

设置为 index-signature 时,强制使用索引签名类型,例如 { [key: string]: unknown }

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/consistent-indexed-object-style": "error"
  }
}
bash
oxlint --deny typescript/consistent-indexed-object-style

参考资料