【问题标题】:Find Cumulative sum React Typescript查找累积和反应打字稿
【发布时间】:2021-11-30 11:38:09
【问题描述】:

我正在尝试查找名为 csTotCommit 的数组列的累积和。我收到以下关于使用数字索引数组的索引错误。

元素隐式具有“any”类型,因为“number”类型的表达式不能用于索引“IBasis”类型。 在 'IBasis'.ts(7053) 类型上未找到带有“number”类型参数的索引签名 关于这个项目:prev[curr.csId]

我可以做些什么不同的事情来索引或从我的数组中获取这个累积总和。

这是我的代码:

  const cumSum = (data: IBasis[]) => {
    data.reduce((prev: IBasis, curr: IBasis) => {
      if (curr.csId && curr.rankId) {

      prev[curr.csId]? prev[curr.csId] += curr.csTotCommit : prev[curr.csId] = curr.csTotCommit
    }
  })
  };

这是我的界面:

export interface IBasis {
  rankId: number | null,
  csTrancheId: number | null,
  csId: number | null,
  csTotCommit: number | null,
  csBasisPerUnit: number | null,
}

【问题讨论】:

    标签: reactjs typescript reduce cumulative-sum


    【解决方案1】:

    reduce函数第一个输入是累加结果。

        const cumSum = (data: IBasis[]) => {
        data.reduce((total: number, curr: IBasis): number => { 
          if (curr.csId && curr.rankId) {
          
           total +=  curr.csId?? 0;   // '?? 0' will add zero when csId is null
           curr.csTotCommit = total;
         }
          return total; // you always have to return cumulative total
      }, 0) // starting with total as zero.
      };
    

    【讨论】:

    • 谢谢,我无法将它作为数组返回。我尝试了 number[],但遇到了问题。
    • 我已经更新了有帮助的答案
    • 感谢 vaira...真的帮助了我。
    猜你喜欢
    • 2021-08-11
    • 1970-01-01
    • 2019-07-11
    • 2023-04-06
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2018-09-29
    • 2023-03-29
    相关资源
    最近更新 更多