初始化对象的类型不存在属性

时间:2019-06-17 23:59:33

标签: javascript arrays typescript object ecmascript-6

我将数据分配给接口的对象。

我已经创建了带有可选字段的界面

export interface IWeek {
    type?: number;
    required?: string;
}


export interface IItem {
    code?: string;
    recipe?: IRecipes;
}

export interface IMenu {
    week?: IWeek;
    items?: IItem[];
    title?: string;
}

然后我将数据分配给对象

const data :IMenu ={} ;
data.week.type=date;
data.title=title;
recipes.map(elm => {
  data.items.push({code:code,recipe:elm})
})

我收到错误消息,表明键入的对象上不存在项目

ERROR in src/app/validation-dialog/validation-dialog.service.ts(13,10): error TS2339: Property 'week' does not exist on type '{}'.
src/app/validation-dialog/validation-dialog.service.ts(14,10): error TS2339: Property 'title' does not exist on type '{}'.
src/app/validation-dialog/validation-dialog.service.ts(16,12): error TS2339: Property 'items' does not exist on type '{}'.

1 个答案:

答案 0 :(得分:0)

您尚未定义属性items。首先将其初始化为空数组。

const data: IMenu = {};
data.items = [];