[Typescript] Use Generics in a Reduce Function

See this code:

const array = [
  {
    name: 'John',
  },
  {
    name: 'Steve',
  },
];

const obj = array.reduce((accum, item) => {
  accum[item.name] = item; // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  return accum;
}, {});

 

As seen in the test, the output looks like this:

{ John: { name: "John", }, Steve: { name: "Steve", }, }

If you imagine that the starting array of data is coming from an API, we don't know the members ahead of time at the type level.

So what we kind of want it to look like is a Record with keys of type string whose values are an object containing a name of type string.

This is reflected in the test:

type tests = [Expect<Equal<typeof obj, Record<string, { name: string }>>>];

 

Solution:

const obj = array.reduce<Record<string, { name: string }>>((accum, item) => {
  accum[item.name] = item;
  return accum;
}, {});

 

posted @ 2023-01-14 01:37  Zhentiw  阅读(22)  评论(0编辑  收藏  举报