Reputation: 11728
How do I initialize an array member in the following class.
class EventObject {
map:Array;
constructor() {
this.map = []; // error :Cannot convert 'any[]' to 'Array'
this.map = new Array(); // error :Cannot convert 'any[]' to 'Array'
};
}
var obj = new EventObject();
console.log(obj.map[0]);
Also, I am able to initialize it if I change the type to number[] . But then, I get an error when I check if it is an instanceof Array :
class EventObject {
map:number[];
constructor() {
this.map = [];
if(this.map instanceof Array) //error here
alert("Type checking");
};
}
I want to do both : initialize and check instanceof (or typeof)
How is the Javascript Array different from an array in Typescript ( represented by '[]' ) ?
Upvotes: 1
Views: 2486
Reputation: 3249
map: number[];
Is the correct syntax.
There's several reasons not to use instacenof Array. See here: Check if object is array?
If you want to use instanceof, you must cast the left operator like:
var m: number[];
if (<any>m instanceof Array) {
}
Upvotes: 3