Lambasoft Lambasoft - 3 days ago 4x
TypeScript Question

Ionic 2 - TypeScript | Populate an array of interface objects

I really did my homework before asking this question, I'm sure some of you would find it foolish, but I'm still kind of new to Typescript and I'm totally struggling with this.

I have an interface:

export interface Product {
name?: string;
image_rul?: string;
description?: string;
price?: number;
quantity?: number;

I'm trying to create an array of type Product and fill that array with random values.

For further explaining myself here's how I'm doing 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_rul: "",
description: "This is a short description",
price: random,
quantity: i

When I run this I get an 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(…)

Please could you lead me to the right direction ? What am I doing wrong or how can I fix it ?

Thanks a lot.


In typescript when you define a class member:

class A {
    member: string[];

It doesn't really create that member in the compiled js code:

var A = (function () {
    function A() {
    return A;

You need to intialize that member:

export class HomePage {
  products: Product[];

  constructor(public navCtrl: NavController) {
    this.products = [];

If you don't do that then it is undefined, which results in the error you posted.

You can also do it when declaring the member:

export class HomePage {
  products: Product[] = [];

Which will result in the same exact js code.