Home > Mobile >  reduce() function in Typescript with instantiate empty object
reduce() function in Typescript with instantiate empty object

Time:12-16

I'm trying to convert my Javascript function to a Typescript version of it but I'm not able to get rid of the read underlined code acc[curr.name] (in VSCode). Which says when hovering over it:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.

I'm counting occurrences by key name.

Where should I define the type and why is an empty object or object with number not working. I'm not sure how to solve it as I tried multiple things, like for example:

data.reduce<{}>() and data.reduce<{property: number}>()

Code:

const data = [
  { name: "name1", },
  { name: "name1", },
  { name: "name1", },
  { name: "name1", },
  { name: "name2", },
  { name: "name2", },
  { name: "name2", },
  { name: "name1", },
];

// count data by key name
const resultData = data.reduce((acc, curr) => {
  return acc[curr.name] ?   acc[curr.name] : (acc[curr.name] = 1), acc;
}, {});

Result when running:

const resultData = {
  name1: 4,
  name2: 3,
  name3: 1,
};

CodePudding user response:

Set a index signature like data.reduce<{ [index: string]: number }>

Ref: https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures

const resultData = data.reduce<{ [index: string]: number }>((acc, curr) => {
  return acc[curr.name] ?   acc[curr.name] : (acc[curr.name] = 1), acc;
}, {});

Or you can use as keyword with initial value.

const resultData = data.reduce((acc, curr) => {
  return acc[curr.name] ?   acc[curr.name] : (acc[curr.name] = 1), acc;
}, {} as { [index: string]: number });
  • Related