Home > Blockchain >  Push key value pair to an existing object in Angular?
Push key value pair to an existing object in Angular?

Time:02-22

I have a object and I want to add one more key value pair to that object, rather than declaring it inside the object declaration. I tried below code but it gives me an error like this.

Property 'specialty' does not exist on type

saveFormData(value: any) {

    const saveData = {
          userPartyRoleId : Number(this.userPartyRoleId),
          notes : thihis.notes,
        };
    
    saveData.speciality = this.spec;
}

CodePudding user response:

This is a TypeScript feature. When you initialize saveData with a value, TypeScript implicitly infers that saveData must have only two properties: userPartyRoleId, notes, and nothing else.

To work around this, you have a few options I can think of.

Solution 1

The most straightforward solution. Just include speciality when initializing saveData. This assigns the correct type for saveData.

const saveData = {
    userPartyRoleId: Number(this.userPartyRoleId),
    notes: this.notes,
    speciality: this.spec
};

Solution 2

As mentioned in the comments, you can use the spread operator. It will create a new object with the correct type, which you will want to assign to a different variable.

const saveData = {
    userPartyRoleId: Number(this.userPartyRoleId),
    notes: this.notes
};

const processedData = {
    ...saveData,
    speciality: this.spec
};

Solution 3

This is a solution in a sense that it will make your code compile without errors, and hopefully run without making more errors down the line. You can use the any type to tell TypeScript to not type-check saveData.

const saveData: any = {
    userPartyRoleId: Number(this.userPartyRoleId),
    notes: this.notes
};

saveData.speciality = this.spec;

With this solution, you will lose TypeScript's strict-typing feature, which is the point of TypeScript in the first place.

  • Related