Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
Sohrab Avatar asked Apr 26 '17 14:04

Sohrab


People also ask

How do you declare an array in TypeScript?

Arrays can be declared and initialized separately. let fruits: Array<string>; fruits = ['Apple', 'Orange', 'Banana']; let ids: Array<number>; ids = [23, 34, 100, 124, 44]; An array in TypeScript can contain elements of different data types using a generic array type syntax, as shown below.

How do you initialize an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you initialize an empty array in TypeScript?

To declare an empty array for a type variable, set the array's type to Type[] , e.g. const arr: Animal[] = [] . Any elements you add to the array need to conform to the specific type, otherwise you would get an error. Copied!

Should I use [] or array in TypeScript?

There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax. They are completely equivalent.


1 Answers

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[] = [];
like image 138
Nitzan Tomer Avatar answered Oct 06 '22 17:10

Nitzan Tomer