TypeScript: tuple type to object type

谁都会走 提交于 2021-02-18 08:23:27

问题


Consider a tuple like this:

type MyTuple = [A, B];

where A and B both have an attribute named key. For instance,

interface A = {
  key: 'sandwiches'
}

interface B = {
  key: 'pasta'
}

I desire the following interface:

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"]
}

but this doesn't work.

This question is the inverse of Typescript: object type to array type (tuple)


回答1:


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>


来源:https://stackoverflow.com/questions/54599480/typescript-tuple-type-to-object-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!