When an Angular2 object property originally designated as "number" suddenly converts to type string

I have a simple Angular2 application running on my local machine. I am using a service to send an object instance to a webservice API, which then validates the JSON data against a schema. The issue I am facing is that when I try to send the object to the webservice, the ID field is enclosed in quotes, even though it is supposed to be a number according to Typescript.

This problem only occurs when the name property of the object contains special characters.

I have confirmed that the issue is not with the JSON.stringify method I am using - please refer to the code snippet below.

The application is coded in Typescript.

Unit class:

export class Unit {
    id: number;
    name: string;
    short: string;
    triggers_plural: number;
    is_headline: boolean;
}

Saving Method:
The following method is used to save an instance of Unit to the webservice:

updateUnit(unit: Unit): Promise<Unit>
{
    var objSend = {unit_data: [unit]};          // Webservice expects an array of units

    console.log(objSend.unit_data[0].id === 2); // Returns false even if ID is set as 2
    console.log(objToReturn);                   // Verifies that ID is 2 during testing

    return this.http.put(`${this.unitUrl}/${unit.id}`, JSON.stringify(objSend),{headers:this.headers})
    .toPromise()
    .then(()=> unit)
    .catch(this.handleError);
}

When calling this method and having the name property of the Unit object containing special characters leads to the ID being treated as a string instead of a number.

Example without special characters (no issue, ID remains a number):

Example WITH special characters (unexpectedly, ID becomes a string):

The updateUnit method is invoked from the unit-detail component, where unit editing takes place:

export class UnitDetailComponent implements OnInit {
    unit: Unit;

    constructor(
        private unitService: UnitService,
        private route: ActivatedRoute
    ){}

    ngOnInit(): void
    {
        this.route.params.forEach((params: Params) => {
            let id = +params['id'];
            this.unitService.getUnit(id)
            .then(unit => this.unit = unit);
        });
    }

    save(): void
    {
        this.unitService.updateUnit(this.unit).then(this.goBack);
    }
}

The unit.name input in the template is bound to an input field:

<div *ngIf="unit">
    <div>
        <label>Edit unit</label>
        <div>
          <input type="text" [(ngModel)]="unit.name" />
        </div>
    </div>
    <button class="btn btn-default" type="button" (click)="save()">Save</button>
</div>

It is possible that the issue arises during two-way data binding when the name property is populated by user input in the <input>, but it is unclear how the id's type changes?

Link to github repository for the entire project: https://github.com/djoike/ng2-cookbook/tree/master-so

Answer №1

An effective approach is to first cast the field as any, and then use parseInt() to convert it to a number. I encountered a similar issue earlier today.

To learn more about casting, refer to the Type assertions section here

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

When using the `.push` method, the array becomes null

Currently, I am in the process of developing an angular application. Within my component's .ts file, there exists an array structured as follows: public myArray = []; public dataFromAPI = []; In a particular method within this component, whenever I ...

Combining operations in Angular using RXJS

I'm struggling with a piece of code in my auth effects file. I'm trying to chain actions but keep encountering errors, indicating that I may not be dispatching the correct Action. I've been exploring options like mergeMap and switchMap, but ...

Connect the backend with the frontend using React.js

I am currently faced with the task of developing the front end for an existing backend project. The original front end was built using Angular, but I am opting to recreate it using React. However, I am unsure about how to establish a connection between t ...

Distinguish between two varieties using parameters

Let's consider the following simplified example: type Reference<T extends {identifier: string}> = T['identifier'] In this type, TypeScript recognizes that it is a reference to an object where the identifier property is of type string ...

Exploring TypeScript's generic features and conditional types in function parameters

Imagine having a function that retrieves the return value of a provided getIdentifier function. This function is necessary, except in cases where the item contains an id property, in which case we can simply read that value. type FuncArg<T> = T exten ...

Error: The Angular test bed is unable to locate the mixpanel definition

Is there a way to test the functionality of the form without considering Mixpanel? I am encountering an error as follows. login.component.ts ngOnInit() { Mixpanel.trackEvent("View Screen", { "Screen Name": "Login" }); this.createForm(); } cr ...

Guide on accessing intellisense for mapGetters, mapActions in Vuex using TypeScript without the need for class-style or decorators syntax

I have been using Vue.js and Vuex for a while now, but always with JavaScript. Recently, I decided to try using Vue with TypeScript, specifically with nuxt.js, but without utilizing decorators or style-class-components. I want to stick to the normal Vue s ...

Is it possible to maintain the component's DOM state when navigating away and then returning in Angular?

After spending several days researching this issue, I find myself at a dead end. I thought I was dealing with a common scenario: A user navigates to a specific page, makes some changes (such as editing an input field, scrolling through grid data, or chang ...

One approach to enhance a function in Typescript involves encapsulating it within another function, while preserving

What I Desire? I aim to create a function called wrap() that will have the following functionality: const func = (x: string) => 'some string'; interface CustomObject { id: number; title: string; } const wrapped = wrap<CustomObject> ...

Searching in Vue based on the selected option is only possible by the selected criteria and not by id, regardless of the

#1 Even if chosen, cannot search by id. The 'name' condition in the loop works well but I am unable to correctly search by id (returns nothing). #2 When selecting an option from the dropdown menu, it only displays until I start typing. I would l ...

Utilizing type inheritance in TypeScript for a handler function

Suppose I have the following code snippet: import { Telegraf } from "telegraf"; const bot = new Telegraf(process.env.BOT_TOKEN || ""); bot.on(message("text"), async (ctx) => { console.log(ctx.message?.text); }); In this ...

Identifying JavaScript Errors in a Web Page: A Guide to Cypress

Currently, I am working on creating a spec file that contains N it(s), with each it visiting a specific page within the application and returning the number of errors/warnings present. I have also shared my query here: https://github.com/cypress-io/cypres ...

Declare, condition, and output all in a single statement

Is there a method to condense the content inside the function below into a single line? I want to avoid declaring check. function Example { const check = this.readByUuidCheck(props) if (check) return this.readByUuid(check) } I am seeking ways to ...

How to Generate a Collection of Textfields in Angular 4

My challenge involves working with an array object that receives input from a textfield. I am looking to create a clean design where only one textfield is initially displayed, along with a '+' button next to it. When the user enters information i ...

What is the process for enabling the isolatedModules=true option when creating a package?

When exporting all the classes from my package in a file, I use lines similar to the following: export {default as BoundList, IBoundListOption, TBoundListFilterFn} from './list/BoundList'; This generates errors like: TS1205: Cannot re-export a ...

the level of zoom in my Angular application automatically goes up when it's in production mode

I have encountered an issue with my Angular application where it appears very zoomed in when hosted on a Node JS server, despite running correctly under the Angular development server. This zoomed-in view is beneficial for readability but ruins the overall ...

Using Angular: Passing a service as a parameter

I have a desire to improve the organization of my code by moving certain functions into an external file and accessing them from multiple components. These functions rely on a service: The MyFunctions Class import { Service1 } from "../_services&quo ...

Suggestions for specifying options with CapacitorSQLite.createSyncTable() when beginning to utilize @capacitor-community/sqlite

Currently, I am following a tutorial on capacitor ionic with sqlite from 2020. Unfortunately, there doesn't seem to be a more recent tutorial available online. (https://youtu.be/2kTT3k8ztL8?t=635) A lot has changed since the tutorial was released, bu ...

PDFJS integration in Ionic 2

Looking for guidance on integrating pdfjs into an ionic2 project. Any suggestions on how to import and use it would be greatly appreciated. Thank you! I'm familiar with using pdfjs, but I'm having trouble figuring out how to bring it into my ion ...

Issue encountered during Angular unit test execution

I encountered an issue while conducting unit testing in Angular. I am attempting to test the creation of a component. Please refer to the error below and help me understand why this problem is occurring. I have also imported the necessary services related ...