Home > Enterprise >  How to turn a tuple of key value pairs into a tuple of values in typescript
How to turn a tuple of key value pairs into a tuple of values in typescript

Time:06-27

I want to create a tuple from the values of a key-value pair tuple

type PairsTuple = [{ k: 1 }, { k: 2 }, { k: 3 }]

type ValuesTuple = ValuesFromPairs<PairsTuple>
// [1, 2, 3]

how would I implement ValuesFromPairs?

CodePudding user response:

This is possible with mapped types:

type ValuesFromPairs<T extends {k: number}[]> = { 
  [K in keyof T]: T[K] extends { k: number } ? T[K]["k"] : never 
}

Playground

CodePudding user response:

Here's a more general solution:

const pairsTuple = [{ k: 1 }, { k: 2 }, { k: 3 }];

type InferValue<T extends Record<any, unknown>> = T extends Record<any, infer I> ? I : never;

type ValuesFromPairs<T extends Record<any, unknown>[]> = { [K in keyof T]: InferValue<T[K]> };

const returnTuple = <T extends Record<any, unknown>[]>(arr: T) => {
    return arr.map((obj) => Object.values(obj)[0]) as ValuesFromPairs<T>;
};

const tuple = returnTuple(pairsTuple);

console.log(tuple);

Only issue is that the type of tuple is number[] instead of [number, number, number]. Same issue with the solution you accepted.

  • Related