Home > Enterprise >  Generic for convert object to tuple of entries
Generic for convert object to tuple of entries

Time:08-07

I search method for convert object type, for example

type a = {
   code: 404,
   hello: 'world'
};

to entries type that have format of tuple

type TypeA = [['code', 404], ['hello', 'world']];
// or
type TypeA = [['hello', 'world'], ['code', 404],];

but still can write only generic that will combine entries elements type in union

type Entries<T> = { [K in keyof T]: [K, T[K]] }[keyof T][];
// it's will generate
type wrongTypeA = (["code", 404] | ["hello", "world"])[]; // it is union

CodePudding user response:

I hope I have warned you enough about why this is not a good idea. For a detailed explanation why this is a bad idea, see the first answer of this post. But either way, we can use the TuplifyUnion type from the answer to construct our type.

type UnionToIntersection<U> =
  (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never
type LastOf<T> =
  UnionToIntersection<T extends any ? () => T : never> extends () => (infer R) ? R : never

// TS4.0 
type Push<T extends any[], V> = [...T, V];

// TS4.1 
type TuplifyUnion<T, L = LastOf<T>, N = [T] extends [never] ? true : false> =
  true extends N ? [] : Push<TuplifyUnion<Exclude<T, L>>, L>

type Entries<T> = TuplifyUnion<keyof T> extends infer U 
  ? {
      [K in keyof U]: [U[K], T[U[K] & keyof T]]
    }
  : never

Here is the result.

type A = {
   code: 404,
   hello: 'world'
};

type TypeA = Entries<A>
//   ^? type TypeA = [["code", 404], ["hello", "world"]]

Playground

  • Related