角度-无法添加属性xxxx,对象不可扩展

时间:2018-09-13 09:04:49

标签: arrays angular typescript

我使用Typescript(角度),但出现此错误:Cannot add property media, object is not extensible

我想在我的步骤对象中添加一个Media元素。在原始Step对象中不包含任何Media数组。

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;

4 个答案:

答案 0 :(得分:1)

我的问题来自@ngrx(不是typeScript)。

答案 1 :(得分:0)

也许尝试一下:

let media = {} as Media;
media["bytes"] = 'foo';

而不是media.bytes。我相信应该可以。

答案 2 :(得分:0)

尝试这样

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

答案 3 :(得分:0)

如果您想即时向对象添加属性,则可以像这样修改界面

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';