0

How to transform a union of objects to a plain union with object's values. An example:

type Foo = {};
type Bar = {};
type Baz = {};
type Qux = {};

type Input = {
  foo: Foo,
  bar: Bar,
} | {
  bar: Bar,
  baz: Baz,
} | {
  qux: Qux,
};

type Expected = Foo | Bar | Baz | Qux;

Pay attention that keys of union's objects may intersect (bar in example). Hope the solution advance me unwrapping nested typings.

TS Playground.

avdotion
  • 105
  • 8

1 Answers1

2

You want to take something like a ValueOf<T> type (which is just T[keyof T]) and distribute it across the union members of T so that if T is, for example, A | B | C, then Transform<T> is A[keyof A] | B[keyof B] | C[keyof C]. You can use a distributive conditional type to get that behavior:

type Transform<T> = T extends any ? T[keyof T] : never;

Let's test it:

type Output = Transform<Input>
// type Output = Foo | Bar | Baz | Qux

Looks good.

Playground link to code

jcalz
  • 264,269
  • 27
  • 359
  • 360