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;
} */
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.