I was thinking if there exists a better/nicer way to negate an instanceof
in Java.
Actually, I\'m doing something like:
if(!(str instanceof String))
You can achieve by doing below way.. just add a condition by adding bracket if(!(condition with instanceOf))
with the whole condition by adding !
operator at the start just the way mentioned in below code snippets.
if(!(str instanceof String)) { /* do Something */ } // COMPILATION WORK
instead of
if(str !instanceof String) { /* do Something */ } // COMPILATION FAIL
No, there is no better way; yours is canonical.
I agree that in most cases the if (!(x instanceof Y)) {...}
is the best approach, but in some cases creating an isY(x)
function so you can if (!isY(x)) {...}
is worthwhile.
I'm a typescript novice, and I've bumped into this S/O question a bunch of times over the last few weeks, so for the googlers the typescript way to do this is to create a typeguard like this:
typeGuards.ts
export function isHTMLInputElement (value: any): value is HTMLInputElement {
return value instanceof HTMLInputElement
}
usage
if (!isHTMLInputElement(x)) throw new RangeError()
// do something with an HTMLInputElement
I guess the only reason why this might be appropriate in typescript and not regular js is that typeguards are a common convention, so if you're writing them for other interfaces, it's reasonable / understandable / natural to write them for classes too.
There's more detail about user defined type guards like this in the docs