0

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

2
  • and more precisely in which language? there is not tag to mark the language. Commented Sep 23, 2018 at 20:16
  • Could you add how you are calling the validateType function, and with what parameters? Commented Sep 24, 2018 at 7:41

1 Answer 1

2

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")
}

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.