[英]Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{}' in TypeScript
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 }
预期的 output 是这样的:
{ '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:这在 JavaScript 中工作正常,但在 TypeScript 中我收到如下错误:
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.我也尝试将元素类型赋予数字,但它没有用。
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键入您的计数应该修复它,我还将删除
element:any
并将其替换为element
因为它的类型应该从您创建数组时推断出来
const count = {} as { [key: number]: number };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.