如何在TypeScript的reduce函数中使用泛型解决类型错误?
解决TypeScript泛型求和函数的类型错误
原代码的问题在于泛型T没有任何约束,TypeScript无法确认传入的key是T的合法属性,也无法保证object[key]是数字类型,所以抛出了类型错误。可以通过添加泛型约束来解决这个问题:
修正后的代码
// 写法1:灵活约束键的合法性,手动指定属性类型为数字 const calculateSum = <T, K extends keyof T>(array: T[], key: K): number => { const total = array.reduce<number>((accumulator, object) => { return accumulator + (object[key] as number); }, 0); return total; }; // 写法2:更严格的约束,直接限定属性值为数字,支持自动推导 const calculateSumStrict = <T extends Record<K, number>, K extends string>(array: T[], key: K): number => { return array.reduce((acc, obj) => acc + obj[key], 0); }; type TProjectServiceList = { id: number; sum: number; }; const services = [ {id: 1, sum: 78.09}, {id: 2, sum: 105.09}, {id: 3, sum: 8.45} ] // 两种写法的使用示例 const totalSum = calculateSum<TProjectServiceList, 'sum'>(services, 'sum'); const totalSumStrict = calculateSumStrict(services, 'sum'); // 无需手动指定泛型,TS自动推导
关键说明
- 写法1通过
K extends keyof T确保key是T的合法属性,再用as number断言属性值为数字,适合你明确知道属性类型的场景。 - 写法2直接在泛型里约束
T必须包含K键且对应值为数字,TypeScript能自动推导泛型参数,安全性和易用性更高。
原错误提示:
object[key] - Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'. No index signature with a parameter of type 'string' was found on type 'unknown'.ts(7053)
内容的提问来源于stack exchange,提问作者Mantoze
相关产品推荐
相关产品推荐

