How to push an object into an array with typescript

Viewed 113094

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[];
}

I have created an object name commentData from class comment to receive all data from form after submit. I also created an object name dish from class Dish. How to push object commentData to object dish.comments

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

My git : https://github.com/zymethyang/Ionic_HKUST

5 Answers

If you need to add multiple objects to an array inside a loop:

let thingsArray = [];

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

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

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

#Answer

Answer on how to push Comment (object) into Dish.comments (array) in TypeScript.


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

View live code on TypeScript Playground and click RUN.

As you see in the above code. You need to change Comment[] into Array<Comment>.

#Explanation

Generic Type Variables

Array<T> or Array<Type>

You may already be familiar with this style of type from other languages such as Java and C#.

We have Generic Type Variables in typescript too.

Another way to use Generic Type Variables:

Here's an example of an array with multiple types:


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

This second version is common if your array consists of different types of objects. For example:

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

View live code on TypeScript Playground and click RUN.

You can learn more about Generic Type Variables here and here

Related