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?
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.
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!
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!
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.
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[] = [];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With