#Extract Key/Value object from tuple type

8 messages · Page 1 of 1 (latest)

fringe stone
#

I have a tuple type MyTuple and want to generate an object from it like so:

type MyTuple = [{ name: 'abc'; value: string }, { name: 'cde'; value: number }];

/*
type ObjectFromNameToValues = {
    abc: string;
    cde: number;
}
*/
type ObjectFromNameToValues = {
  [Name in MyTuple[number]['name']]: Extract<MyTuple[number], { name: Name }>['value'];
};

The comment shows the final inferred type of ObjectFromNameToValues

Now, this works, but it’s incredibly wasteful to fetch the subtypes of my tuple with [number] and then infer the value type with Extract. Is there any way to refer to the index of the tuple to use it? Something like

type ObjectFromNameToValues = {
  [Name in MyTuple[number as Idx]['name']]: MyTuple[Idx]['value'];
};
bright saddle
#

does this work?

type ObjectFromNameToValues = {
  [Name in MyTuple[number]["name"]]: Extract<MyTuple[number], { name: Name }>["value"];
};
fringe stone
#

Yes, that’s from the first code snippet

narrow lagoon
#

Use as renaming.

#
type MyTuple = [{ name: 'abc'; value: string }, { name: 'cde'; value: number }]

type Result = {
    [T in MyTuple[number] as T['name']]: T['value']
}
#

!ts Result

split jasperBOT
#
type Result = {
    abc: string;
    cde: number;
} /* 3:6 */```
fringe stone
#

That works! amazing, than you