简体   繁体   中英

Typescript: Transform a union of objects to a plain union

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 .

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 A | B | C A | B | C , then Transform<T> is A[keyof A] | B[keyof B] | C[keyof C] A[keyof A] | B[keyof B] | C[keyof C] 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM