让我们在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>>
游乐场