Reputation: 843
The if statement below evaluates to true when type is a string and I can't seem to figure out why. This is my code:
const validateType = (instanceDescription, type) => {
if (!type instanceof Type) {
throw new Error(`type property of ${instanceDescription} is not
a (child) instance of class Type`);
}
}
I can't see the problem being in my class because it's really simple. It looks like this.
class Type {
constructor(key, multipliers) {
this.multipliers = multipliers;
this.key = key;
}
}
Is there something going on with the instanceof comparison that I'm not aware of or am I just going mad. I got around it by checking if a certain property is undefined which it will be for a string but I would rather go for the more clear instanceof option
Upvotes: 0
Views: 34
Reputation: 92440
Parenthesis make a difference here because of operator precendence. !
has a higher precedence than instanceof
so with out the parenthesis your test is asking if false
is an instance of Type
:
class Type {
constructor(key, multipliers) {
this.multipliers = multipliers;
this.key = key;
}
}
let t = "somestring"
if (!(t instanceof Type)) { // << note the parenthesis
console.log("error")
}
if (!t instanceof Type) { // << never fires
console.log("no error")
}
Upvotes: 2