本文介绍了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:元组类型到对象类型
发布评论