I'm trying to calculate the bank balance in my application from a query from my backend that has the following result:
{
"previousBalance": 60,
"data": [
{
"id": "6fbc24fa-7262-4c82-8944-134201ca2524",
"bank_statement_id": "3d3a6fdc-66e3-412e-9c3a-493681a0504e",
"date": "2021-02-24T03:00:00.000Z",
"value": 333.33
},
{
"id": "98e1c331-a2cc-4e6c-b466-6e778bb1ad10",
"bank_statement_id": "d62c2bbb-fcf1-4227-9bdb-e7f7ba00099d",
"date": "2021-02-24T03:00:00.000Z",
"value": -200
},
{
"id": "1ede9e5c-3b29-450a-bfa3-655ab62ed489",
"bank_statement_id": "d62c2bbb-fcf1-4227-9bdb-e7f7ba00099d",
"date": "2021-02-24T03:00:00.000Z",
"value": -68.33
}
]
}
With that, it aimed to leave in each transaction, the balance value of each transaction with the following logic
type Transaction = {
id: string,
bank_statement_id: string,
date: string,
value: number,
created_at: string,
updated_at: string,
}
const transactions: Transaction[] = [...];
const transactionsFormated = transactions.map((transaction:, index) => {
const totalBalance = transactions.reduce((acc: number, transaction, currentIndex) => {
if(currentIndex <= index) {
return acc transaction.value;
}
return acc;
});
return {
...transaction,
balance: previousBalance totalBalance,
}
});
However, the VSCode points out that the acc parameter is of type Transaction, instead of type number, in addition to the message as in the title of this post.
How can I proceed with this problem in question?
CodePudding user response:
You are missing the second parameter of the reduce method, which is the initial value; without that, the initial value is the first element of the array, which is a transaction.
...
const totalBalance = transactions.reduce((acc: number, transaction, currentIndex) => {
if(currentIndex <= index) {
return acc transaction.value;
}
return acc;
}, 0); // <=== here add the initial value
...