#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