简体   繁体   English

元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引 TypeScript 中的“{}”类型

[英]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.

相关问题 Typescript 元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引类型 - Typescript Element implicitly has an 'any' type because expression of type 'any' can't be used to index type TypeScript 错误:“元素隐式具有 'any' 类型,因为类型 'any' 的表达式不能用于索引类型 - TypeScript Err: "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type TypeScript 错误元素隐式具有“任何”类型,因为“任何”类型的表达式不能用于索引类型 - TypeScript error Element implicitly has an 'any' type because expression of type 'any' can't be used to index type TypeScript:元素隐式具有“any”类型,因为“any”类型的表达式不能用于索引“Assignable”类型 - TypeScript: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Assignable' Typescript 错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型 - Typescript Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type TypeScript 错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{}” - TypeScript Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}' TypeScript:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型 - TypeScript: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type TypeScript - 元素隐式具有“任何”类型,因为类型“字符串”的表达式不能用于索引类型“TestObject” - TypeScript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'TestObject ' TypeScript - 元素隐式具有“any”类型,因为“storyFile”类型的表达式不能用于索引类型“{}” - TypeScript - Element implicitly has an 'any' type because expression of type '“storyFile”' can't be used to index type '{}' React typescript - 元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引类型 - React typescript - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM