TypeScript:元组类型到对象类型 [英] TypeScript: tuple type to object type
本文介绍了TypeScript:元组类型到对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑这样的元组:
type MyTuple = [A, B];
其中A
和B
都有一个名为key
的属性.例如,
where A
and B
both have an attribute named key
. For instance,
interface A = {
key: 'sandwiches'
}
interface B = {
key: 'pasta'
}
我想要以下界面:
interface Result {
sandwiches: A;
pasta: B;
}
有没有办法动态地做到这一点?
Is there a way to do this dynamically?
我在想,如果这是可以实现的,它可能看起来像:
I'm thinking that, if this is achievable, it might look something like:
type MapTuple<T> = {
[K in keyof T]: T[K]["key"]
}
但这不起作用.
这个问题是 Typescript 的逆:对象类型到数组类型(元组)
This question is the inverse of Typescript: object type to array type (tuple)
推荐答案
这将产生预期的效果.您需要映射元组的所有键属性并为每个键提取元组成员:
This will produce the desired effect. You need to map over all the key properties of the tuple and extract the tuple member for each key :
type MyTuple = [A, B];
interface A {
key: 'sandwiches'
}
interface B {
key: 'pasta'
}
type MapTuple<T extends Array<{ key: string }>> = {
[K in T[number]['key']]: Extract<T[number], { key : K}>
}
type R = MapTuple<MyTuple>
这篇关于TypeScript:元组类型到对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文