Angular - Cannot add property xxxx, object is not extensible

Viewed 7989

I Use Typescript (Angular) And I have this error: Cannot add property media, object is not extensible

I want add a Media element in My step Object. At the origine Step object do not contain any Media array.

export interface Step {
  duration: string;
  instructions: string;
  ingredients_instructions?: string;
  ingredients?: Quantity[];
  media?: Media[];
  action?: CookingAction;
}

export interface Media {
  id: string;
  author: string;
  license: string;
  creation_date: string;
  modification_date: string;
  bytes: string;
}

stepsSelection: Step[] = [];
...
const media = {} as Media;
media.bytes = 'foo';
media.license = 'DR';
this.stepsSelection[i].media = [ ];
this.stepsSelection[i].media[0] = media;
2 Answers

Try like this

this.stepsSelection[i] = {};    
this.stepsSelection[i]['media'] = [];
this.stepsSelection[i].media[0] = media;

If you want to add properties to the object on the fly, you can modify your interface like that

export interface Step {
  duration: string;
  instructions: string;
  ingredients_instructions?: string;
  ingredients?: Quantity[];
  action?: CookingAction;
  [prop: string]: any;
}

const step = {} as Step;
const media = {} as Media;
step.media = [ media ];
step.foo = 'bar';
Related