[Typescript] Map an Object to a Union of Tuples

We start with a Values interface:

interface Values {
  email: string;
  firstName: string;
  lastName: string;
}

 

We want a union of tuple [key, value]as result:

type tests = [
  Expect<
    Equal<
      ValuesAsUnionOfTuples,
      ["email", string] | ["firstName", string] | ["lastName", string]
    >
  >,
];

 

Solution:

type ValuesAsUnionOfTuples = {
  [V in keyof Values]: [V, Values[V]];
}[keyof Values];

 

posted @ 2022-12-13 15:31  Zhentiw  阅读(25)  评论(0编辑  收藏  举报