Reduce函数的几个Typescript(不能赋予类型参数)错误

问题描述 投票:1回答:1
[ts]
Argument of type '(sum: number, wallet: IConvertedRate) => number' is not assignable to parameter of type '(previousValue: number, currentValue: "" | { convertedRate: number; }, currentIndex: number, array: ("" | { convertedRate: number; })[]) => number'.

Types of parameters 'wallet' and 'currentValue' are incompatible.
Type '"" | { convertedRate: number; }' is not assignable to type 'IConvertedRate'.
Type '""' is not assignable to type 'IConvertedRate'. [2345]

不确定如何解决这些Typescript错误

日志

这就是wallets的样子:

[
  { currency: 'USD', amount: 100 },
  { currency: 'EUR', amount: 500 }
  { currency: 'CHF', amount: 10000 }
]

这就是convertedRates的样子:

[
  { convertedRate: 100 },
  { convertedRate: 437,44 }
  { convertedRate: 9980.9 }
]

下面的代码工作并返回正确的10518.34总值,但无法摆脱打字稿错误。

interface IConvertedRate {
  convertedRate: number;
}

calculateTotalValue(wallets: IWallet[]) {
  const { assets } = this.props;

  const convertedRates = wallets.map((wallet) => {
    const conversion = assets.filter((asset) => asset.currency === wallet.currency)[0];

    if (conversion) {
      return {
        convertedRate: roundFloat(wallet.amount * conversion.rate, 2)
      };
    }

    return '';
  });

  const total = convertedRates.reduce(function(sum: number, wallet: IConvertedRate) {
    return sum + wallet.convertedRate;
  }, 0);

  console.log('total', total);
  return total.toString();
}

enter image description here

javascript typescript reduce
1个回答
2
投票

问题是你的map函数的主体返回return '';,所以convertedRates的签名是''|IConvertedRate。您需要重写map函数的主体以始终返回IConvertedRate,或者强制执行转换

© www.soinside.com 2019 - 2024. All rights reserved.