首页 > 解决方案 > 初始化对象的类型不存在属性

问题描述

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

我用可选字段创建了我的接口

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 '{}'.

标签: javascriptarraystypescriptobjectecmascript-6

解决方案


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

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

推荐阅读