4

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

1 Answer 1

11

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 });
Sign up to request clarification or add additional context in comments.

2 Comments

Great, thank you for your answer! Would you be so kind and add also a link to the documentation. Thanks.
@BenjaminK I've updated the post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.