Skip to main content

no-redundant-type-constituents

Disallow members of unions and intersections that do nothing or override type information.

💭

该规则需要 类型信息 才能运行。


某些类型可以覆盖并集或交集中的某些其他类型 ("constituents") 和/或被某些其他类型覆盖。 TypeScript 的类型集合论包括组成类型在父并集或交集中可能无用的情况。

英:Some types can override some other types ("constituents") in a union or intersection and/or be overridden by some other types. TypeScript's set theory of types includes cases where a constituent type might be useless in the parent union or intersection.

| 联合内:

英:Within | unions:

  • anyunknown "override" 所有其他联合成员
  • never 在任何位置从联合中删除,除了在返回类型位置时
  • 原始类型,例如 string "override" 任何其字面量类型,例如 ""

& 交集内:

英:Within & intersections:

  • anynever "override" 所有其他交集成员
  • unknown 从十字交集掉下
  • 字面量类型 "override" 交集中的任何原始类型
  • 字面量类型,例如 "" "override" 任何原始类型,例如 string
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-redundant-type-constituents": "error"
}
};
在线运行试试这个规则 ↗

示例

type UnionAny = any | 'foo';
type UnionUnknown = unknown | 'foo';
type UnionNever = never | 'foo';

type UnionBooleanLiteral = boolean | false;
type UnionNumberLiteral = number | 1;
type UnionStringLiteral = string | 'foo';

type IntersectionAny = any & 'foo';
type IntersectionUnknown = string & unknown;
type IntersectionNever = string | never;

type IntersectionBooleanLiteral = boolean & false;
type IntersectionNumberLiteral = number & 1;
type IntersectionStringLiteral = string & 'foo';
Open in Playground

局限性

此规则很安全,仅适用于底部类型、顶部类型以及将字面量类型与原始类型进行比较。

英:This rule plays it safe and only works with bottom types, top types, and comparing literal types to primitive types.

何时不使用它

出于文档目的,某些项目有时会故意包含冗余类型成分。 例如,以下代码在联合中包含 string,即使 unknown 使其变得多余:

英:Some projects choose to occasionally intentionally include a redundant type constituent for documentation purposes. For example, the following code includes string in a union even though the unknown makes it redundant:

/**
* Normally a string name, but sometimes arbitrary unknown data.
*/
type NameOrOther = string | unknown;

如果你强烈偏好这些不必要的类型成分,则此规则可能不适合你。

英:If you strongly feel a preference for these unnecessary type constituents, this rule might not be for you.

进一步阅读

选项

该规则不可配置。

资源