In TypeScript, combining the numbers 0 and 1 results in the value 01

I am in the process of developing a Shopping Card feature.

private _card: Map<Product, number> = new Map<Product, number>();

...

addToCard(prod: Product, amount: number = 1): void {
    const totalAmount: number = this._card.get(prod) + amount; // Calculating the total amount
    console.log(this._card.get(prod) + ' + ' + amount);
    this._card.set(prod, totalAmount);
  }

Log:

card.service.ts:31 0 + 1
card.service.ts:31 01 + 1
card.service.ts:31 011 + 2
card.service.ts:31 0112 + 2
card.service.ts:31 01122 + 3
card.service.ts:31 011223 + 4

It seems that instead of performing normal addition, the result is being concatenated. I have verified that all variables are declared as numbers.

Thank you for any assistance provided.

Answer №1

If you want to increase the card value by a certain amount, you can simply convert the card value into a number and then add the specified amount

addToCard(prod: Product, amount: number = 1): void {
    const a: number = +this._card.get(prod) + +amount; // Calculating the new total
    console.log(this._card.get(prod) + ' + ' + amount);
    this._card.set(prod, a);
}

Answer №2

let sum:number = parseInt(this._card.get(prod), 10) + parseInt(amount, 10);

To ensure both values are treated as numbers, consider using parseInt with a strict base of 10.

Another alternative is to try:

 let sum:number = this._card.get(prod) += amount;

It's possible that one of the variables, such as prod, is mistakenly being interpreted as a string, leading to concatenation instead of addition.

Answer №3

The rationale behind this issue is that calling this._card.get(cord) retrieves a string value, but you can easily modify it as shown below:

addToCart(product: Product, quantity: number = 1): void {
    const totalQuantity: number = +this._cart.get(product) + quantity; // Adding the current quantity with new items
    console.log(this._cart.get(product) + ' + ' + quantity);
    this._cart.set(product, totalQuantity);
  }

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

TS7053: The element is implicitly assigned an 'any' type as the expression of type 'string' cannot be used to index the type '{ username: string; email: string; '

Having trouble incorporating TypeScript into a custom React Form Component, and I keep encountering an error that I can't seem to resolve. Error message TS7053: Element implicitly has an 'any' type because expression of type 'string&apo ...

The issue lies with the Cookies.get function, as the Typescript narrowing feature does not

Struggling with types in TypeScript while trying to parse a cookie item using js-cookie: // the item 'number' contains a javascript number (ex:5) let n:number if(typeof Cookies.get('number')!== 'undefined'){ n = JSON.pars ...

Join and Navigate in Angular 2

Attempting to retrieve information from a JSON file has been an issue for me. Here is the code snippet: ngOnInit() { this.http.get('assets/json/buildings.json', { responseType: 'text'}) .map(response => response) .subsc ...

I am curious if there exists a VSCode plugin or IDE that has the ability to show the dependencies of TypeScript functions or provide a visual representation

Are there any VSCode plugins or IDEs available that can display the dependency of TypeScript functions or show a call stack view? I am looking for a way to visualize the call stack view of TypeScript functions. Is there a tool that can help with this? Fo ...

The Angular HttpClient Service will exclusively provide responses that have a status code of 200

I'm facing an issue with my login component where it calls an http client service to send a request to the server for logging in. Everything works smoothly when I enter valid credentials, but if I input wrong credentials, the service doesn't seem ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

Error message in Angular 8: Cannot be assigned to AsyncValidatorFn

I am currently working on implementing a custom validator function in a reactive form. Here is the code snippet: form.component.ts ... form = new FormGroup({ username: new FormControl('', [ Validators.required, ...

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

Encountering an error in Cytoscape using Angular and Typescript: TS2305 - Module lacks default export

I am working on an Angular app and trying to integrate Cytoscape. I have installed Cystoscape and Types/cytoscape using npm, but I encountered an error when trying to import it into my project. To troubleshoot, I started a new test project before implement ...

Can Angular Universal help pinpoint the location of a window reference error?

My Angular Universal project was running smoothly until I added a significant amount of code and included some external npm libraries like Quill. Now, I am encountering a Reference error related to the window object. It seems that every time I reference wi ...

Fetching values from JSON object using Key in Angular

Here is the code snippet for the markup and component in question: new.component.html <a routerLink="{{sub.name}}" routerLinkActive="active">{{sub.name}}</a> old.component.ts data; this.route.params.subscribe((params:any) => {console.lo ...

What is the best way to execute a sequence of http requests only after the previous one has been completed successfully, while also addressing any

Working with Angular/rxjs 6 has brought me to a challenge. I'm struggling to get an observable sequence to run smoothly as intended. Here's the concept of what I'm trying to achieve: Request received to change systems: Check permissions Fe ...

In Angular, is there a way to transform time into the format of YYYY-MM-DDThh:mm:ssTZD?

Our backend is built with Java and we are using the ISO 8601 standard for date formatting. In order to pass dates in this format, I require a method to convert the date into the specified format. In Java, we use: DateFormat iso8601 = new SimpleDateFormat( ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

Angular : How can a single item be transferred from an array list to another service using Angular services?

How to Transfer a Single List Item to the Cart? I'm working on an Angular web application and I need help with transferring a single item from one service to another service and also displaying it in a different component. While I have successfully i ...

Exploring the potential of Angular 5 in combination with Apache and secure

I am currently facing a challenge with my Angular 5 application. I need to ensure that all traffic is redirected to Https if it's not already using Https. Unfortunately, the only access I have is to the .htaccess file for configuration. Initially, I ...

Tips for testing two conditions in Angular ngIf

I am facing a little issue trying to make this *ngIf statement work as expected. My goal is to display the div only if it is empty and the user viewing it is the owner. If the user is a guest and the div is empty, then it should not be shown. Here is my cu ...

Sending various arguments within a single post request in Angular 6 and Node.js

I am currently developing an app in Angular 6 using NodeJS + Mongoose. I have two parameters that need to be sent to the backend with a single POST request. My query is, is it possible to include both parameters in one POST Request? Thank you The paramet ...

Using Typescript to extract and process keys of a certain type from an object

I am dealing with an object type that has keys corresponding to values of various types, including number, string, optional number, and optional string: interface MyObject { mandatoryNumber: number; optionalNumber?: number; mandatoryString: string; ...

What is the best way to obtain the dimensions of an image in Angular 2 (or newer) before uploading it to the server, and can this be accomplished without utilizing jQuery?

After searching through multiple resources, I realized that most of the solutions are written in jQuery. However, I am specifically looking for a solution in Typescript. The HTML code snippet is as follows: <input #coverFilesInput class="file-input" t ...