TN.
TN.

Reputation: 19850

How to blend union type into partial type in TypeScript?

Let's have the following type in TypeScript:

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

What is the simplest way to blend it in a partial type:

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

Essentially, I am looking for a type Blend<T>:

type Blend<T> = ...

So, I can define Result as following:

type Result = Blend<Input>

Upvotes: 0

Views: 371

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 38006

You can use union to intersection wrapped with Partial:

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

type Blend<T> = Partial<UnionToIntersection<T>>

Playground

Upvotes: 2

Related Questions