Skip to content
← Back to rules

typescript/no-empty-object-type 限制

An auto-fix is available for this rule.

它做了什么

为了避免 {} 类型允许任何非空值所带来的混淆,此规则禁止使用 {} 类型。这包括没有任何字段的接口和对象类型别名。

为什么这是不好的?

TypeScript 中的 {}(即“空对象”类型)是那些不熟悉 TypeScript 结构类型系统的开发者常见的困惑来源。{} 表示任意非空值,包括像 0"" 这样的字面量。 通常,开发者写下 {} 时实际上想表达的是:

  • object:表示任意对象值
  • unknown:表示任意值,包括 nullundefined

换句话说,“空对象”类型 {} 实际上意味着“所有已定义的值”。它包括数组、类实例、函数以及字符串、符号等原始值。

请注意,此规则不会报告以下情况:

  • {} 作为交集类型中的类型组成部分(例如,TypeScript 内置的 type NonNullable<T> = T & {}),因为这在类型系统操作中可能很有用。
  • 从多个其他接口继承的接口。

示例

此规则的 错误 代码示例:

ts
let anyObject: {};
let anyValue: {};
interface AnyObjectA {}
interface AnyValueA {}
type AnyObjectB = {};
type AnyValueB = {};

此规则的 正确 代码示例:

ts
let anyObject: object;
let anyValue: unknown;
type AnyObjectA = object;
type AnyValueA = unknown;
type AnyObjectB = object;
type AnyValueB = unknown;
let objectWith: { property: boolean };
interface InterfaceWith {
  property: boolean;
}
type TypeWith = { property: boolean };

配置

此规则接受一个配置对象,包含以下属性:

allowInterfaces

type: "never" | "always" | "with-single-extends"

default: "never"

是否允许空接口。

允许的值为:

  • 'always':始终允许无字段的接口
  • 'never' (默认):从不允许无字段的接口
  • 'with-single-extends':允许仅从单个基接口扩展而来的空接口

使用 { allowInterfaces: 'with-single-extends' } 时的 正确 代码示例:

ts
interface Base {
  value: boolean;
}
interface Derived extends Base {}

allowObjectTypes

type: "never" | "always"

default: "never"

是否允许空对象类型字面量。

允许的值为:

  • 'always':始终允许无字段的对象类型字面量
  • 'never' (默认):从不允许无字段的对象类型字面量

allowWithName

type: string

一个字符串化的正则表达式,用于允许具有指定名称的接口和对象类型别名。

当现有代码风格中存在使用 {} 而非 object 声明空类型的情况时,此选项非常有用。

使用 { allowWithName: 'Props$' } 时的 错误 代码示例:

ts
interface InterfaceValue {}
type TypeValue = {};

使用 { allowWithName: 'Props$' } 时的 正确 代码示例:

ts
interface InterfaceProps {}
type TypeProps = {};

如何使用

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

json
{
  "rules": {
    "typescript/no-empty-object-type": "error"
  }
}
bash
oxlint --deny typescript/no-empty-object-type

参考资料