Even after putting in the effort to research before posting this question, I'm aware that some might consider it trivial. However, as a newcomer to Typescript, I am facing considerable challenges with it.
Let me start by showing you my interface:
export interface Product {
name?: string;
image_url?: string;
description?: string;
price?: number;
quantity?: number;
}
My goal is to create an array of type Product and populate it with random values.
To give you a clearer picture, here's how I'm attempting to achieve it:
export class HomePage {
products: Product[];
constructor(public navCtrl: NavController) {
for (var i=0; i< 10; i++) {
var random: number = Math.floor(Math.random() * 10) + 1;
this.products[i] = <Product>{
name: `Test_${i}`,
image_url: "https://unsplash.it/200/?random",
description: "This is a short description",
price: random,
quantity: i
};
}
console.log(this.products);
}
}
However, upon running this code, I encounter the following error:
polyfills.js:3 Error: Uncaught (in promise): Error: Error in ./HomePage class HomePage_Host - inline template:0:0 caused by: Cannot set property '0' of undefined(…)
I would greatly appreciate if you could provide guidance on where I am going wrong or suggest ways to rectify the issue.
Thank you very much.