将 Union 类型转换为 Intersection 类型

Convert Union type to Intersection type

我正在尝试将联合类型转换为交集类型:

type UnionToIntersection<U> = // unknown code

type test = UnionToIntersection<{a: 1} | { b: 2}>
// typeof test should be {a: 1} & { b: 2}, an impossible type

这只是大型函数中的一个步骤,该函数随后会将 {a:1}{b:2} 的属性合并为 {a:1, b:2}。但那是后面的步骤。

第一步是我需要将并集转换为交集。我该怎么做?


对于那些想知道的人,它将进入这个:

export type SubpropertyMerge<T> = (
  T extends (...args: infer A) => infer R ? (
    (...args: A) =>  R
  ): (
    T extends object ? (
      T extends string | number | ((...args: any) => any) | symbol | boolean ? T
      : { [K in keyof T]: SubpropertyMerge<T[K]> }
    ) : T
  )
);

// SubpropertyMerge<{a: 1} & { b: 2}> === {a:1, b:2}

您可以使用此 UnionToIntersection 类型:

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