【问题标题】:Angular - Cannot add property xxxx, object is not extensible [closed]Angular - 无法添加属性 xxxx,对象不可扩展 [关闭]
【发布时间】:2019-02-17 23:39:14
【问题描述】:

我使用 Typescript (Angular) 我有这个错误:Cannot add property media, object is not extensible

我想在我的步骤对象中添加一个媒体元素。在原始 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;

【问题讨论】:

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

标签: arrays angular typescript


【解决方案1】:

这样试试

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

【讨论】:

  • this.stepsSelection[i] = {}; => 不可能将 {} 分配给 Step 类型
  • 是的,因为当您创建对象时,您不尊重您的界面。您声明了一些强制变量。将 ? 放在 StepMedia 界面中的所有变量中,它将起作用。或者,如果您想保留它们,则需要在将对象分配给 Step[] 类型时传递它们。不知道我的解释是否清楚
【解决方案2】:

如果你想动态地为对象添加属性,你可以像这样修改你的界面

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

【讨论】:

  • 对不起,我不想修改Step界面(不是我的项目)
  • 然后试试这个:stepsSelection[i] = { media: [ media ] };
  • 另外,这不是一个好的解决方案。它允许您添加任何对象。您将失去严格输入的所有好处...
猜你喜欢
  • 2020-06-07
  • 2021-02-02
  • 1970-01-01
  • 2019-08-29
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 2020-06-23
相关资源
最近更新 更多