首页 > 解决方案 > TypeScript – 对象数组联合的值产生交集,而不是联合

问题描述

有两个不同对象的数组(数组a和数组b),这些数组的联合的成员值 - (a | b)[number]- 产生它们的交集,而我希望有一个联合:

type a = { one: string }[];
type b = { one: string, two: string }[];

type ab = (a | b)[number]; // actual type:   { one: string }
                           // expected type: { one: string } | { one: string, two: string }

另请参阅TypeScript playground 的链接

我想知道:

  1. 派生类型{ one: string }是否正确?
  2. 为什么不是{ one: string } | { one: string, two: string }
  3. 有没有办法实现expected任意对象数组的类型?

谢谢!

标签: typescript

解决方案


是的,派生类型是正确的,但通常不是预期的。

这就是联合在 TS 中的工作方式。

考虑下一个例子:

type a = { one: string };
type b = { one: string, two: string };

type ab = keyof (a | b); // "one"

TS 将返回one,因为此密钥可在两种类型(a,b)之间共享。

为了实现所需的行为,您可以尝试分布式条件类型

当条件类型作用于泛型类型时,它们在给定联合类型时变得可分配

type a = { one: string }[];
type b = { one: string, two: string }[];

type ArrayValues<T> = T extends Array<infer Elem> ? Elem : never

type Result = ArrayValues<a | b> // { one: string } | { one: string, two: string }

操场


推荐阅读