0

I have code like this:

const arr = [3, 3, 2, 1, 4, 5];

const count = {};

arr.forEach((element:any) => {
  count[element] = (count[element] || 0) + 1;
});
console.log(count);

The expected output is like this: { '1': 1, '2': 1, '3': 2, '4': 1, '5': 1 }

This works fine in JavaScript, but in TypeScript I am getting an error like this:

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}'.

I have tried giving type of element to number also but it did not work.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • The problem is that Typescript does not know what `arr` is, so it assumes it's an object. At least, I think that's the problem. If you change your declaration of `arr` so that you give it the appropriate array type, that might help. – Pointy Aug 15 '22 at 12:41
  • 1
    @Pointy it can infer `number[]` just fine, the OP _explicitly_ widened `element` to `any` for reasons that are not clear. – jonrsharpe Aug 15 '22 at 12:43
  • Does this answer your question? [Element implicitly has an 'any' type because expression of type 'string' can't be used to index](https://stackoverflow.com/questions/57086672/element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b) – angel.bonev Aug 15 '22 at 12:45
  • @jonrsharpe ah, well that's nice. So it figures that `any` doesn't necessarily have a useful string representation, which is reasonable. – Pointy Aug 15 '22 at 12:47

1 Answers1

2

Typing your count should fix it, I'd also remove element:any and just replace it with element as its type should be inferenced from when you create the array

const count = {} as { [key: number]: number };

Jacob Stephenson
  • 544
  • 3
  • 13