typescript - 如何使用 typescript 将对象插入数组

标签 typescript

我有一个数组名称 dish 和一个表格。表单提交后,数据推送到盘中。我尝试使用 push 方法将其添加到数组中,但它有错误。我怎么能用 typescript 做到这一点? 非常感谢你。 类对象。

export interface Dish {
   id: number;
   name: string;
   image: string;
   category: string;
   label: string;
   price: string;
   featured: boolean;
   description: string;
   comments: Comment[];
}

我已经从类评论中创建了一个对象名称 commentData,以便在提交后接收来自表单的所有数据。我还从类 Dish 创建了一个对象名称 dish。如何将对象 commentData 推送到对象 dish.comments

export interface Comment {
   rating: number;
   comment: string;
   author: string;
   date: string;
}

我的混帐:https://github.com/zymethyang/Ionic_HKUST

最佳答案

let myArray = [];
let commentData = {} as Dish;
commentData.id = 3;
commentData.name = 'something';
myArray.push(commentData);

它会工作...

关于typescript - 如何使用 typescript 将对象插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46249472/

相关文章:

typescript - 如何正确导入反射元数据

javascript - Typescript React <Select> onChange 处理程序类型错误

typescript - .NET Core 和 Angular 2 工作流程

基于第一个参数的函数参数动态类型

javascript - 错误 : *. default is not a constructor

typescript - 使用 @types/history 中的 createBrowserHistory() 时出现 Tslint 错误

angular - 向返回 promise 的 javascript 方法添加延迟

multithreading - 多线程 Firebase 函数

typescript - 如何修复 `declared but its value is never read` 误报?

angular - 无法为奇数行和偶数行设置单独的颜色