Skip to content
← Back to rules

typescript/no-redundant-type-constituents Correctness

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

它的作用

此规则禁止联合类型和交叉类型中冗余的类型构成项。

为什么这有问题?

由于 TypeScript 的类型系统规则,联合类型和交叉类型的某些构成项可能是冗余的。这些冗余的构成项不会增加任何价值,反而会使类型更难阅读和理解。

示例

此规则的错误代码示例:

ts
// unknown 在联合类型中是冗余的
type T1 = string | unknown;

// any 在联合类型中是冗余的
type T2 = string | any;

// 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;

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "options": {
    "typeAware": true
  },
  "rules": {
    "typescript/no-redundant-type-constituents": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  options: { typeAware: true },
  rules: {
    "typescript/no-redundant-type-constituents": "error",
  },
});
bash
oxlint --type-aware --deny typescript/no-redundant-type-constituents

版本

此规则是在 v1.12.0 中添加的。

参考资料