How to transform union of similar objects to object type using TypeScript typings?
type I = {
key: 'foo',
value: Foo,
} | {
key: 'bar',
value: Bar,
};
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With