Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: tuple type to object type

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)

like image 307
jamesplease Avatar asked Oct 31 '25 15:10

jamesplease


1 Answers

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>
like image 78
Titian Cernicova-Dragomir Avatar answered Nov 03 '25 09:11

Titian Cernicova-Dragomir