Home > other >  Cannot assign to read only property 'x' of object '[object Object]'
Cannot assign to read only property 'x' of object '[object Object]'

Time:10-05

After upgrading my project to Angular 12/TypeScript 4.3.5, I am getting the error above. Here is my code:

for (const metric of metrics) {
    if (!metric.focalThemeSubArea) {
        metric.focalThemeSubArea = metric.focalTheme;
    }
}

My Metric class is defined as follows:

export class ScaMetricGraphType {
    public focalTheme: string;
    public focalThemeSubArea: string;
    public isActive: boolean;
    public name: string;
}

I don't see anything that's read-only about focalThemeSubArea. While it's true that I declared metric as const in the loop, that shouldn't mean that its members become read-only. Unless something changed about TypeScript that I'm unaware of.

CodePudding user response:

You can not declare const inside the loop, instead it is better to use let.

CodePudding user response:

Use let instead of const inside for loop

CodePudding user response:

Try this instead, maybe this will work.

metric['focalThemeSubArea'] = metric['focalTheme']
  • Related