1

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 '[]' ) ?

1
  • To answer How is the Javascript Array different from an array in Typescript ( represented by '[]' ) ?, they should be equivalent : typescript.codeplex.com/workitem/812 Commented Mar 20, 2013 at 5:31

1 Answer 1

3
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) {
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.