[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();
}
问题是你的map
函数的主体返回return '';
,所以convertedRates
的签名是''|IConvertedRate
。您需要重写map函数的主体以始终返回IConvertedRate
,或者强制执行转换