Sohrab Sohrab - 17 days ago 94
TypeScript Question

How to initialize an array of numbers 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?

Answer Source

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