首页 > 其他分享 >[Typescript] Use Generics in a Reduce Function

[Typescript] Use Generics in a Reduce Function

时间:2023-01-14 01:56:10浏览次数:36  
标签:Function Use Typescript name type Steve item John accum

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;
}, {});

 

标签:Function,Use,Typescript,name,type,Steve,item,John,accum
From: https://www.cnblogs.com/Answer1215/p/17051079.html

相关文章