Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

426
Views
reduce() function in Typescript with instantiate empty object

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,
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!