【问题标题】:How can I build a Type that has all the properties from an array of Types?如何构建具有类型数组中所有属性的类型?
【发布时间】:2019-12-12 17:42:27
【问题描述】:

假设我有两种类型(例如,我需要一些通用的)

type TypeA = { propA: string};
type TypeB = { propB: number};

我想写一个通用类型,让我可以做这样的事情

type ABMerge = ArrayMerge<[TypeA,TypeB]>

// ABMerge would look like { propA: string, propB: number }

我尝试过使用泛型和条件类型,但我不知道如何“迭代”我的泛型类型数组。

【问题讨论】:

  • 可能是类型交集&amp; ?
  • 别以为你可以用数组类型来做到这一点。

标签: typescript typescript-generics


【解决方案1】:

诀窍是首先使用T[number] 将所有数组元素“叠加”到一个元素上。 这为我们提供了所有类型的联合(例如 TypeA | TypeB)。

因为你想要一个交集类型 (TypeA &amp; TypeB),然后我们可以使用 this answer 中的巧妙技巧将该联合转换为交集。

完整示例:

type UnionToIntersection<U> =
    (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never

type ArrayMerge<T extends Array<any>> = UnionToIntersection<T[number]>;

// Test it:
type TypeA = { propA: number };
type TypeB = { propB: string };

const ab: ArrayMerge<[TypeA, TypeB]> = {
    propA: 42,
    propB: "x",
};

ab.propA; // number
ab.propB; // string

查看playground

【讨论】:

  • 非常感谢马丁,这正是我要找的!
【解决方案2】:

您可以在 Typescript 中简单地使用类型交集运算符&amp;

type A = { propA: number };
type B = { propB: string };

type AB = A & B;

const ab: AB = {
    propA: 42,
    propB: "hello, world",
};

See on the playground

【讨论】:

  • 对不起,我觉得我的问题说得不够清楚,但我并不总是知道类型 A 和 B,这就是为什么我需要更通用的东西
  • @RamaRivera 你不需要提前知道类型 A 和 B。你可以使用A &amp; B,就像你在不知道a和b的情况下写a + b一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2013-11-22
  • 1970-01-01
相关资源
最近更新 更多