Skip to content
← Back to rules

typescript/no-redundant-type-constituents 正确性

This rule is turned on by default when type-aware linting is enabled.
💭 This rule requires type information.

它做了什么

此规则禁止在联合类型和交集类型中使用冗余的类型组成部分。

为什么这是不好的?

由于 TypeScript 类型系统的规则,某些联合类型和交集类型的组成部分可能是冗余的。这些冗余的组成部分没有任何价值,反而会使类型更难阅读和理解。

示例

以下为该规则的 错误 代码示例:

ts
// union 中的 `unknown` 是冗余的
type T1 = string | unknown;

// union 中的 `any` 是冗余的
type T2 = string | any;

// union 中的 `never` 是冗余的
type T3 = string | never;

// 比其他类型更宽的字面量类型
type T4 = string | "hello";

// 是子集的对象类型
type T5 = { a: string } | { a: string; b: number };

以下为该规则的 正确 代码示例:

ts
type T1 = string | number;

type T2 = "hello" | "world";

type T3 = { a: string } | { b: number };

// 交集中使用 `unknown` 有意义
type T4 = string & unknown;

// 交集中使用 `never` 有意义
type T5 = string & never;

如何使用

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

json
{
  "rules": {
    "typescript/no-redundant-type-constituents": "error"
  }
}
bash
oxlint --type-aware --deny typescript/no-redundant-type-constituents

参考资料