Sohrab
Sohrab

Reputation: 1478

How to initialize (declare) an array in TypeScript?

I am absolute beginner on TypeScript. I want to initialize an array of numbers in TypeScript by "for" loop as you see in the following:

 public hours: number[];
 constructor() {
   for (let i: number = 1; i < 25; i++) {
      this.hours[i] = i;
    }
  }

I get an error: Cannot set property '1' of undefined. Could you please help me?

Upvotes: 12

Views: 25514

Answers (2)

JusMalcolm
JusMalcolm

Reputation: 1431

hours isn't set to any value. You can create a new array in the constructor, or set hours to an empty array:

public hours: number[] = [];
constructor() {
   for (let i: number = 1; i < 25; i++) {
      this.hours[i] = i;
   }
}

Upvotes: 1

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

This line:

public hours: number[];

Does not create a new array, it only declares it.
If you compile this code:

class MyClass {
    public hours: number[];

    constructor() {
        for (let i: number = 1; i < 25; i++) {
            this.hours[i] = i;
        }
    }
}

You get:

var MyClass = (function () {
    function MyClass() {
        for (var i = 1; i < 25; i++) {
            this.hours[i] = i;
        }
    }
    return MyClass;
}());

As you can see, this.hours isn't being assigned.

So you need to do this:

constructor() {
    this.hours = [];

    for (let i: number = 1; i < 25; i++) {
        this.hours[i] = i;
    }
}

Or:

public hours: number[] = [];

Upvotes: 19

Related Questions