简体   繁体   中英

Typescript: Convert union of similar objects to object type

How to transform union of similar objects to object type using TypeScript typings?

Input

type I = {
  key: 'foo',
  value: Foo,
} | {
  key: 'bar',
  value: Bar,
};

Output

type O = {
  foo: Foo,
  bar: Bar,
};

I am not sure it is possible. But who knows? Note that the task is not a duplicate to that .

In TypeScript 4.1 this is a straightforward mapped type with key remapping . You can iterate over each member T of the I union (it's a union, not an intersection) and look up the key/value types: T['key'] for the key and T['value'] for the value. Like this:

type O = { [T in I as T['key']]: T['value'] };
/* type O = {
    foo: Foo;
    bar: Bar;
} */

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