如何在reduce函数中使用typescript

问题描述 投票:0回答:1

我的代码:

const calculateSum = <T>(array: T[], key: string): number => {
  const total = array.reduce<number>((accumulator, object: T) => {
    return accumulator + object[key];
  }, 0);

  return total;
};

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>(services, 'sum');

我收到打字稿错误:

object[key] - 元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“unknown”类型。在“未知”类型上找不到带有“字符串”类型参数的索引签名。ts(7053)

如何使用打字稿泛型来制作这个函数?

javascript typescript typescript-generics reduce
1个回答
0
投票

calculateSum
的定义中没有提到T的类型是什么。所以编译器显然不知道
T
的键值的类型。因此,出现错误。

鉴于您正在尝试添加这些值,我想假设这些值都是

number
类型。现在有一个解决方案:

const calculateSum = <T extends { [id : string] : number}>(array: T[], key: string): number => {
  const total = array.reduce<number>((accumulator, obj: T) => {
    return accumulator + obj[key];
  }, 0);

  return total;
};

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>(services, 'sum');
© www.soinside.com 2019 - 2024. All rights reserved.