如何使用TypeScript将对象推入数组

25

我有一个名为dish的数组和一个表单。表单提交后,数据被推送到dish中。我尝试使用push方法将其添加到数组中,但是出现了错误。我该如何使用TypeScript进行操作? 非常感谢。 Class对象。

i have an array name dish and have a form. After the form submited, data push to dish. I have tried to use push method to add that into an array, but it's have error. How i can do that with typescript ? Thanks you very much. Class object.

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

我已经从类“comment”创建了一个名为“commentData”的对象,以接收提交表单后的所有数据。我还从类“Dish”创建了一个名为“dish”的对象。如何将对象“commentData”推入对象“dish.comments”中?

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

我的 git 仓库链接:https://github.com/zymethyang/Ionic_HKUST


1
请在您的对象中添加代码。 - Dr. X
我已经编辑了我的帖子。请在顶部检查。谢谢。 - Tri Nguyen
5个回答

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

它会工作...


抱歉,但我有新的评论并希望将其推送到现有的dish.comments中。 - Tri Nguyen

8

#答案

如何在TypeScript中将Comment(对象)推入Dish.comments(数组)的解决方法。


export interface Dish {
   id: number;
   name: string;
   image: string;
   category: string;
   label: string;
   price: string;
   featured: boolean;
   description: string;
   // comments: Comment[]; // remove this
   comments: Array<Comment>; // <--- change to this. everytime you want to add array use Array<YourInterface>
}

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

dish.comments.push(commentData);


TypeScript Playground 上查看实时代码,并单击 RUN

如您所见,需要将Comment[]更改为Array<Comment>

#解释

泛型变量

Array<T>Array<Type>

您可能已经从其他语言(如Java和C#)熟悉了这种类型的类型。

在typescript中,我们也有泛型变量。

使用泛型变量的另一种方式:

以下是一个包含多种类型的数组示例:


let x: Array<string | number>
x = ["hello", "world", 2]

如果你的数组包含不同类型的对象,那么第二种版本很常见。例如:

interface Boat {
  name: string
}

interface SpaceShip {
  code: number
}

interface Wagon {
  active: boolean
}

let inventory: Array<Boat | SpaceShip | Wagon> = [];

let boatData: Boat = {
  name: "Boat 1"
}

let spaceShipData: SpaceShip = {
  code: 1234
}

let wagonData: Wagon = {
  active: true
}

inventory.push(boatData);
inventory.push(spaceShipData);
inventory.push(wagonData);

console.log(inventory);

TypeScript Playground 上查看实时代码,并点击RUN

您可以在这里在这里了解有关泛型类型变量的更多信息。


@Nima,我的回答有什么问题吗?我纠正了他的代码(回答了如何在TypeScript中将对象推入数组),并解释了如何使用通用类型变量来更多地了解这种类型的内容。 - Rem
@Nima,你可以阅读我的更新答案,并添加了一个链接到TypeScript Playground,以编辑代码来向你展示我的答案是可行的。 - Rem
  1. 实际上,从OP的问题来看,Array<...>Comment[]没有任何区别!
  2. dish.comment.push({/*所有字段都应该有值的评论*/});
  3. 我的playground链接太长了,无法在此处放置....
- Mamrezo

6
如果你只需要在每次表单提交后添加新的commentData(如果我理解正确的话),那么你所需要的就是每次想要将新评论推送到现有的dish.comments时使用以下内容:
this.dish.comments = this.dish.comments.push(this.commentData); // assuming these are class properties, hence the 'this' usage

你觉得这个方案可行吗?

编辑

修改第一行

this.commentData = this.comment.value;

dismiss()方法中,将this作为参数传入:

this.commentData.author = this.comment.get('author').value;
this.commentData.rating = this.comment.get('rating').value;
this.commentData.comment = this.comment.get('comment').value;

是的,那就是我想要的,但它不起作用。 [ts] 类型“数字”不能分配给类型“Comment[]”。 (属性)Dish.comments: Comment[] - Tri Nguyen
有趣,number 是从哪里来的?你能展示一下你的 commentData 对象的例子吗? - amal
评论数据对象示例。{ "rating": 5, "comment": "想象所有的食品,生活在混乱之中!", "author": "约翰·莱蒙", "date": "2012-10-16T17:57:28.556094Z" }, - Tri Nguyen
如果你的模型(接口)中有任何一个与其对应的对象不完全匹配,那么就会出现这个错误。也许你需要检查一下对象结构,并在接口声明中使用 ? 符号来“可选化”某些属性,例如:rating?: number; - amal
这是我的 Git https://github.com/zymethyang/Ionic_HKUST。你能帮我修复一下吗?这是 comment.ts 上的 dismiss() 方法。谢谢。 - Tri Nguyen
显示剩余2条评论

4

如果你需要在循环内向数组中添加多个对象:

let thingsArray = [];

someArray.forEach(doc => {
    let thingsObj = {} as Thingy;

    thingsObj.weekDue = doc.name;
    thingsObj.title = doc.age;
    thingsArray.push(thingsObj);

}).then(() => {
    console.log(thingsArray);
}

1

let arraylist = [];
let obj1 = {} as Class;
obj1.id = 1;
obj1.name = 'text';
let obj2 = {} as Class;
obj2.id = 1;
obj2.name = 'text';
arraylist = [obj1, obj2];

这对我来说很有效,但是我试过它使用类。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接