Home > Enterprise >  Typescript convert dictionary list to array dictionary with correct infered type
Typescript convert dictionary list to array dictionary with correct infered type

Time:09-07

I want a situation like this:

const before = [
  { id: 1, name: 'apple' },
  { id: 2, name: 'banana' },
  { id: 3, name: 'melon' },
]

to

const after = {
  id: [1, 2, 3],
  name: ['apple', 'banana', 'melon']
}

So, I wrote the logic as below.

const unzip = (arr) => {
  if (!arr) return {};
  return arr.reduce((acc, cur) => {
    Object.keys(cur).forEach(key => {
      acc[key] = [...(acc[key] ?? []), cur[key]];
    });
    return acc;
  }, {});
};

Then the type should be guessed like this: But it is not.

const after = unzip(before);
after // <- It is infered to be 'any'.

The above "after" should be typed as follows.

after // { id: number[], name: string[] }

How should I use Generic?

CodePudding user response:

You're really just taking each element and making the values into arrays:

type Unzip<T> = {
  [K in keyof T]: T[K][];
};

And then we use generics to infer and "store" the type of each element, returning the unzipped version:

const unzip = <T>(arr: T[]): Unzip<T> => {

Playground

  • Related