Using Typescript to reduce an array of objects results in concatenation

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!

Answer №1

After examining the code, two issues became apparent:

The first problem:

I discovered that one of the amount elements in my array was a string. Removing this element resolved the concatenation problem, as the reduce method will concatenate values if they are strings.

The second issue:

Upon fixing the first problem, I realized that my reducer was returning an object to be processed next. Upon debugging, I learned that reduce utilizes the return value from the callback function for the next iteration. In my case, I was mistakenly trying to access the return value as an object in the following code snippet:

const total = items.reduce((acc, i) => acc + i.amount, 0)

The problem here is that the variable acc is an object. To perform the calculation correctly, I should return an object with the amount property like this:

const total = expenses.reduce((accumulator, expense) => ({
    ...expense,
    amount: accumulator.amount + expense.amount,
}));

It is important to note the spreading of the expense object as well, as the expenses object contains properties that the new accumulator object was lacking.

By implementing the changes outlined above, I was able to achieve the desired outcome of obtaining the total sum of all amounts in my array of objects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason that *(str+i) = *(str +j) is ineffective in this scenario?

void reverseString(char *str){ int i, j; char temp; for(i = 0, j = strlen(str) - 1; i < j; i++, j--){ temp = *(str + i); *(str + i) = *(str + j); *(str + j) = temp; printf("%c", *(str + j)); } } int mai ...

Tips for outputting data in TypeScript when a search form is updated

Below is the structure of my HTML file: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type"" content="text/html; charset=utf-8"/> </head> <body> <input ...

Ways to combine all similar key values into an array

Apologies if the question seems unclear. Essentially, I am dealing with an object structured as follows: [{"6":6.5},{"4":4.2},{"6":6.3}] My goal is to eliminate duplicate keys while preserving their values, and merge them into a single unique key, formin ...

Consolidate type definition within a tsx file using VS Code

Whenever I define a type in a TypeScript file (.ts) on VS Code, I notice that there is no option to collapse the definition. Here's an example: export type Test = { someValue: string, someOtherValue: string, yetAnotherValue: string }; I ...

Error: The function visitor.visitUnaryOperatorExpr is not defined as a function

I recently started developing an Angular app with a purchased template and collaborating with another developer. Initially, I was able to successfully build the project for production using ng build --prod. However, when trying to build it again yesterday, ...

Upgrade your project from Angular 5 to Angular 9 using webpack

I want to share my experience, not ask a question! To upgrade dependencies in package.json: -Update all Angular dependencies to version 9 -Add these dependencies: "@angular-devkit/build-angular": "^0.900.4", "@angular-builders/cu ...

Encountering an Eslint issue: "Function missing return type" while adding a styled component to _document.tsx in Next.js

Setting up my NextJS project with styled components and Typescript has been my current focus. After consulting the official NextJS documentation, I successfully configured the _document.tsx file, which appears like this: import Document, { DocumentContext ...

Sort attributes by the type of property

Is there a way to create a customized type by extracting specific properties from a generic type? class Test { value1!: Date value2!: number value3!: Date value4!: string } type FilterProperties<T, TFieldType> = //looking for a solution to se ...

Excluding certain source files in Typescript's tsconfig is a common practice to

My attempt to configure Typescript to exclude specific files during compilation is not working as expected. Despite setting exclusions in my tsconfig.json file, the code from one of the excluded files (subClassA.ts) is still being included in the compiled ...

What is the reason behind a tuple union requiring the argument `never` in the `.includes()` method?

type Word = "foo" | "bar" | "baz"; const structure = { foo: ["foo"] as const, bar: ["bar"] as const, baX: ["bar", "baz"] as const, }; const testFunction = (key: keyof typeof sche ...

TS2339: The 'contacts' property is not found within the 'Navigator' type

I am currently developing a contacts application that utilizes the Apache Cordova plugins for contacts. However, when attempting to run the npm run bundle command for my application, I encountered the error mentioned in the title above. Can anyone guide me ...

Incorrectly selecting an overload in a Typescript partial interface can lead to errors

My attempt to define an overload for my function using a Partial interface overloading is causing typescript to select the incorrect overload interface Args { _id: string; name: string; } interface Result { _id: string; name: string; } function my ...

Getting the current browser window in the renderer within Electron 14: A step-by-step guide

Previously, I utilized the code below to retrieve the current window from the renderer: import {remote, BrowserWindow} from 'electron'; export function getCurrentWindow(): BrowserWindow { return remote.getCurrentWindow(); } With electron 14 ...

TSLint throws an error, expecting either an assignment or function call

While running tslint on my angular project, I encountered an error that I am having trouble understanding. The error message is: expected an assignment or function call getInfoPrinting() { this.imprimirService.getInfoPrinting().subscribe( response => ...

Modifying a group of Components in Angular using a Service

Managing a set of Components involves changing their properties using a Service. The Components have a minimal model and are meant to remain compact. They are being rendered with *ngFor. The Service possesses a large Object and should possess the abilit ...

Exploring the power of NestJS integration with Mongoose and GridFS

I am exploring the functionality of using mongoose with NestJs. Currently, I am leveraging the package @nestjs/mongoose as outlined in the informative documentation. So far, it has been functioning properly when working with standard models. However, my p ...

Using jQuery to populate an array with selected table items

Issue Description: I am working on an HTML page with two add buttons and two tables. Currently, when the add button is clicked, rows are appended to their respective tables. However, in the backend, I need to gather all row elements when a specific "button ...

An effective method for excluding null values with an Angular pipe

I am currently working on an Angular pipe that filters results based on user input. The problem I'm encountering is that some of the results do not have a value, resulting in this error message: Cannot read property 'toLocaleLowerCase' o ...

The type '{}' is lacking the specified attributes from type 'RouteComponentProps<{},,>'

As a newcomer to React and Typescript, I'm in the process of familiarizing myself with both. Please bear with me as I navigate through this learning curve! index.tsx Router.tsx (containing all route definitions) LandingFrame.tsx (defining the page la ...

Intellisense in VS Code is failing to provide assistance for data within Vue single file components

I am working with a simple code snippet like this https://i.sstatic.net/JSEWJ.png However, within the method, the variable 'name' is being recognized as type any. Interestingly, when I hover over 'name' in the data, it shows up as a s ...