Reputation: 961
I have a strange problem and it's clear that my error is about understanding something on instantiating class in Typescript.
In My code I've write it
let res:Array<MyClass>=[];
......
console.log(res[0] instanceof MyClass)
the expression in console.log() return me a false value, why?
And second question, is it possible to do something like
res instanceof Array<MyClass>
?
I have even try to check the type in this way
typeof res[0]==="MyClass"
still same problem, always get false
Upvotes: 0
Views: 127
Reputation: 7641
This could happens in case of empty array:
class MyClass {
}
let res: Array<MyClass> = [];
console.log(res[0]);
console.log(res[0] instanceof MyClass); // false because res is empty and res[0] is undefined
res.push(new MyClass());
console.log(res[0]);
console.log(res[0] instanceof MyClass); // true
I've created corresponding jsfiddle.
Upvotes: 2