Best way to “negate” an instanceof

后端 未结 9 1313
后悔当初
后悔当初 2021-01-30 02:01

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


        
9条回答
  •  后悔当初
    2021-01-30 02:42

    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

提交回复
热议问题