no-duplicate-type-constituents
Disallow duplicate constituents of union or intersection types.
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
该规则需要 类型信息 才能运行。
TypeScript 支持并集内的类型 ("constituents") 和交集类型彼此重复。 然而,开发者通常期望每个成分在其交集或并集内都是唯一的。 重复的值会使代码过于冗长,并且通常会降低可读性。
英:TypeScript supports types ("constituents") within union and intersection types being duplicates of each other. However, developers typically expect each constituent to be unique within its intersection or union. Duplicate values make the code overly verbose and generally reduce readability.
该规则不允许重复的并集或交集成分。
如果类型在类型系统中计算出相同的结果,我们认为类型是重复的。
例如,给定 type A = string
和 type T = string | A
,此规则将标记 A
与 string
的类型相同。
英:This rule disallows duplicate union or intersection constituents.
We consider types to be duplicate if they evaluate to the same result in the type system.
For example, given type A = string
and type T = string | A
, this rule would flag that A
is the same type as string
.
- ❌ 不正确
- ✅ 正确
type T1 = 'A' | 'A';
type T2 = A | A | B;
type T3 = { a: string } & { a: string };
type T4 = [1, 2, 3] | [1, 2, 3];
type StringA = string;
type StringB = string;
type T5 = StringA | StringB;
Open in Playgroundtype T1 = 'A' | 'B';
type T2 = A | B | C;
type T3 = { a: string } & { b: string };
type T4 = [1, 2, 3] | [1, 2, 3, 4];
type StringA = string;
type NumberB = number;
type T5 = StringA | NumberB;
Open in Playgroundmodule.exports = {
"rules": {
"@typescript-eslint/no-duplicate-type-constituents": "error"
}
};
选项
ignoreIntersections
当设置为 true 时,将忽略对交集类型成分的重复检查。
英:When set to true, duplicate checks on intersection type constituents are ignored.
ignoreUnions
当设置为 true 时,将忽略联合类型成分的重复检查。
英:When set to true, duplicate checks on union type constituents are ignored.
何时不使用它
有时,出于文档目的,包含同一类型的别名可能很有用。 你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。
英:It can sometimes be useful for the sake of documentation to include aliases for the same type. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.
在某些情况下,品牌类型 可能是表示基础数据类型的类型安全方式。
选项
该规则接受以下选项
type Options = [
{
ignoreIntersections?: boolean;
ignoreUnions?: boolean;
},
];
const defaultOptions: Options = [
{ ignoreIntersections: false, ignoreUnions: false },
];