TypeScript分组Product数组时对象索引无显式类型错误的解决方法
TypeScript按Product.type分组时的编译错误解决方法
问题背景
我有一个Product类型的数组,类定义如下:
class Product { id: string; type: string; price: number; constructor(id: string, type: string, price: number) { this.id = id; this.type = type; this.price = price; } }
尝试使用Array.reduce按type属性对产品数组分组,代码如下:
const groupedProducts = productList.reduce((group, prod) => { const prodType = prod.type; group[prodType] = group[prodType] ?? []; group[prodType].push(prod); return group; }, {});
但编译时出现错误:
No index signature with a parameter of type 'string' was found on type '{}'.
我意识到初始值{}缺少显式的索引类型,尝试改成{string: Product[]}但问题仍未解决。
解决方案
方法1:给初始值指定Record工具类型
直接通过类型断言给reduce的初始值标注Record<string, Product[]>类型,明确对象的键为字符串、值为Product数组:
const groupedProducts = productList.reduce((group, prod) => { const prodType = prod.type; group[prodType] = group[prodType] ?? []; group[prodType].push(prod); return group; }, {} as Record<string, Product[]>);
方法2:显式定义累加器类型
在reduce的回调函数中,直接给累加器group指定类型,初始值保持{}即可:
const groupedProducts = productList.reduce((group: Record<string, Product[]>, prod) => { const prodType = prod.type; group[prodType] = group[prodType] ?? []; group[prodType].push(prod); return group; }, {});
方法3:使用尖括号类型断言(旧语法)
如果你习惯TypeScript的旧语法,也可以用尖括号给初始值指定类型:
const groupedProducts = productList.reduce((group, prod) => { const prodType = prod.type; group[prodType] = group[prodType] ?? []; group[prodType].push(prod); return group; }, <Record<string, Product[]>>{});
关键说明
你之前尝试的{string: Product[]}是错误的语法,TypeScript中正确的索引签名写法是[key: string]: Product[],而Record<string, Product[]>是官方提供的工具类型,本质和手动写索引签名等价,但更简洁规范,专门用来表示“键为某类型、值为某类型”的对象结构。
内容的提问来源于stack exchange,提问作者user842225
相关产品推荐
相关产品推荐

