Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 683
avdotion Avatar asked Nov 16 '25 17:11

avdotion


1 Answers

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

like image 145
jcalz Avatar answered Nov 18 '25 08:11

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!