0

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>
TN.
  • 18,874
  • 30
  • 99
  • 157
  • Does this answer your question? [Transform union type to intersection type](https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type) – Yury Tarabanko Nov 02 '20 at 15:40
  • @YuryTarabanko I do not want to transform union type to intersection type. I want to get partial type. However, Aleksey uses the answer provided there in his solution. – TN. Nov 03 '20 at 09:26
  • But the answer you have accepted does exactly that :) with obvious additional step. It even links the question I have mentioned. So this is basically a dup. – Yury Tarabanko Nov 03 '20 at 10:08
  • @YuryTarabanko Is it duplicated answer or duplicated question? – TN. Nov 03 '20 at 10:24

1 Answers1

2

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

Aleksey L.
  • 35,047
  • 10
  • 74
  • 84
  • 1
    Thank you, I have fixed the title. – TN. Nov 02 '20 at 15:34
  • Can you give a short explanation as to why you need the `UnionToIntersection` magic here? Wouldn't simply using `Partial` also work? – tomcek112 Nov 02 '20 at 15:39
  • 1
    @tomcek112 you're right, in this specific example simple `Partial` would do. But technically it produces a union and if you'd like to do some further processing - it will remain union (not what requested by OP) https://www.typescriptlang.org/play?#code/C4TwDgpgBAkgdmArsKBeKBvAUFXUCGAXFAM7ABOAlnAOY54BGxciAtgxOVgL5QA+mergDGxMlVo8sWUJCgAlCCUQAbFOkUBHRJXIQAJgB4ACvnLBK+FYfhJgAPnvThAezhko5YouVq0mAmIAciCAGihRKCCARiCoXgB6BKg4FyhOchdyKEBeDcAEPawgA – Aleksey L. Nov 02 '20 at 15:51