如何使用打字稿将对象推入数组

Tri*_*yen 6 typescript

我有一个数组名菜,有一种形式。表格提交后,数据推送到盘中。我尝试使用push方法将其添加到数组中,但是有错误。我如何用打字稿做到这一点?非常感谢你。类对象。

export interface Dish {
   id: number;
   name: string;
   image: string;
   category: string;
   label: string;
   price: string;
   featured: boolean;
   description: string;
   comments: Comment[];
}
Run Code Online (Sandbox Code Playgroud)

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

export interface Comment {
   rating: number;
   comment: string;
   author: string;
   date: string;
}
Run Code Online (Sandbox Code Playgroud)

我的git:https : //github.com/zymethyang/Ionic_HKUST

Dr.*_*. X 10

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

它会工作...


Rem*_*Rem 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);

Run Code Online (Sandbox Code Playgroud)

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

正如您在上面的代码中看到的。你需要改变Comment[]Array<Comment>.

#解释

通用类型变量

Array<T>或者Array<Type>

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

我们在打字稿中也有通用类型变量。

使用通用类型变量的另一种方法:

下面是一个具有多种类型的数组的示例:


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

Run Code Online (Sandbox Code Playgroud)

如果您的数组由不同类型的对象组成,则第二个版本很常见。例如:

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

Run Code Online (Sandbox Code Playgroud)

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

您可以在此处此处了解有关通用类型变量的更多信息


ama*_*mal 6

如果您只需要commentData在每次提交表单后添加新的评论(如果我理解正确的话),那么每次您希望将新评论推送到现有的评论时,您所需要的就是这个dish.comments

this.dish.comments = this.dish.comments.push(this.commentData); // assuming these are class properties, hence the 'this' usage
Run Code Online (Sandbox Code Playgroud)

那对你有用吗?

编辑

修改第一行

this.commentData = this.comment.value;
Run Code Online (Sandbox Code Playgroud)

dismiss()此方法中,

this.commentData.author = this.comment.get('author').value;
this.commentData.rating = this.comment.get('rating').value;
this.commentData.comment = this.comment.get('comment').value;
Run Code Online (Sandbox Code Playgroud)