In my quest to calculate the sum of integers from an array of objects stored in a redux slice, I have encountered a challenge. Here is the code snippet in question:
export type Expense = {
id: string;
title: string;
amount: number;
date: string;
};
type ExpensesState = {
expenses: Expense[];
};
const initialState: ExpensesState = {
expenses: [],
};
The reduce function I am using is as follows:
const total = expenses.reduce(
(accumulator, expense) => accumulator + expense.amount,
0
);
I suspect that the issue lies with the type of my array of objects. To demonstrate, here is an example that works as expected:
const items = [{foo: 'bar', amount: 1}, {foo: 'bar', amount: 12}]
const total = items.reduce((acc, i) => acc + i.amount, 0)
console.log(total) // 13
The type of items in the above example is:
type items = { foo: string, amount: number }[]
However, when I attempt to modify the array type causing the problem to match the items type like this, I still encounter issues with summing the amounts:
export type Expense = {
id: string;
title: string;
amount: number;
date: string;
}[];
If anyone can provide assistance, I would greatly appreciate it as I am currently stuck in a loop trying to solve this problem!