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]

Not sure how to address these Typescript errors

logs

This is what wallets looks like:

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

This is what convertedRates looks like:

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

This code below works and returns the correct total value of 10518.34, but can't get rid of the typescript error.

Code

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

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

1 Answers1

2

The problem is that the body of your map function returns return '';, so signature of convertedRates is ''|IConvertedRate. You need to rewrite the body of the map function to always return an IConvertedRate, or you force a cast

rpadovani
  • 7,101
  • 2
  • 31
  • 50