Search code examples
angularngrxngrx-store

Ngrx Selector Cannot assign to read only property


after angular upgrade from 7 to 14.i am getting error in selector.ts file.i am using ngrx store.i am getting error

Cannot assign to read only property 'x' of object.

below is the code which throwing the error.

function mapXAndY(points: CloudDataPoint[], delta: boolean) {
     return points.map(point => {
        point.x = delta ? point.costDelta : point.cost;
        point.y = delta ? point.riskDelta : point.risk;
        return point;
    });
}

Solution

  • You probably marked x and y in your CloudDataPoint type as readonly. The moment you attempt to re-assign this, it will error out.

    type CloudDataPoint = {
      readonly x: number;
      readonly y: number;
      costDelta: number;
      cost: number;
      riskDelta: number;
      risk: number;
    }
    

    You probably want to create a new object, add a new value for x and y and pass the other properties along unchanged.

    function mapXAndY(points: CloudDataPoint[], delta: boolean) {
      return points.map(point => {
        return {
          ...point,
          x: delta ? point.costDelta : point.cost,
          y: delta ? point.riskDelta : point.risk,
        };
      });
    }