You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript统计数组元素次数报错:Element implicitly has an 'any' type

解决TypeScript统计数组元素出现次数的类型报错问题

问题原因

你遇到的报错是因为TypeScript对空对象{}的类型推断默认是{}(无任何可索引属性),当你用数字类型的element去索引这个对象时,TypeScript无法确认该索引的合法性,因此抛出类型错误。即使把element设为number,只要count的类型没明确,问题依然存在。

解决方案

方案一:显式定义count的类型

直接给count指定Record<number, number>类型(表示键为数字、值为数字的对象),代码如下:

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

const count: Record<number, number> = {};

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

方案二:使用字符串类型的键(更符合对象键的实际表现)

由于JavaScript对象的键最终会被转为字符串,你也可以将count的类型定义为Record<string, number>,并把数字元素转为字符串作为键:

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

const count: Record<string, number> = {};

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

方案三:类型断言(临时快速解决)

如果不想显式定义类型,也可以用类型断言告诉TypeScriptcount的预期类型,但这种方式不如显式定义类型规范:

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

const count = {} as Record<number, number>;

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

以上三种方案都能解决类型报错问题,且运行后都能得到你预期的输出结果。

内容的提问来源于stack exchange,提问作者upendradhamaladev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 14:06:25