Home > Mobile >  Typescript tuple to object type
Typescript tuple to object type

Time:02-22

Suppose I have a tuple type like this:

type Test<T extends string, V> = { type: T, value: V };
type Tuple = [
    Test<'string', string>, 
    Test<'number', number>, 
    Test<'integer', number>
];

From the type Tuple I would like to generate the type

type TupleObject = {
    string: string,
    number: number,
    integer: number,
};

Is this at all possible and if so, how? So far I have only managed to get

type TupleObject = {
    string: string | number,
    number: string | number,
    integer: string | number,
};

CodePudding user response:

You can use a mapped type with an as clause and map over Tuple[number]

type TupleToObject<T extends Array<Test<string, any>>> = {
    [K in T[number] as K['type']]: K['value']
}

Playground Link

  • Related