[英]Typescript: Convert union of similar objects to object type
How to transform union of similar objects to object type using TypeScript typings?如何使用 TypeScript 类型将相似对象的联合转换为 object 类型?
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 .在 TypeScript 4.1 中,这是一个简单的映射类型,带有键重新映射。 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.您可以遍历
I
联合的每个成员T
(它是联合,而不是交集)并查找键/值类型: T['key']
用于键, T['value']
用于值。 Like this:像这样:
type O = { [T in I as T['key']]: T['value'] };
/* type O = {
foo: Foo;
bar: Bar;
} */
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.