如何在TypeScript中将并集类型混合为分部类型



让我们在TypeScript中使用以下类型:

type Input = {
a: string
b: number
} | {
c: string
}

将其混合为部分类型的最简单方法是什么:

type Result = {
a?: string
b?: number
c?: string
}

本质上,我正在寻找一种类型Blend<T>:

type Blend<T> = ...

因此,我可以将Result定义为:

type Result = Blend<Input>

您可以使用并集来交叉包装Partial:

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

游乐场

最新更新