mautrok
mautrok

Reputation: 961

typescript instanceof my class evaluated as any

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>

?

Update

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

Answers (1)

TSV
TSV

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

Related Questions