javascripttypescriptecmascript-5custom-errors

How to cast a variable to a particular type to convince typescript that everwhere?


For IE reasons I need to build a custom Error, however, as best as I can do it, the error has to be checked with the constructor.

customError instanceof CustomError; // false
customError.constructor === CustomError; // true

Now how can I convince typescript that in an if statement?

if (customError.constructor === CustomError) {
  customError.customMethod1() // typescript complaints
  customError.customMethod2() // typescript complaints
  customError.customMethod3() // typescript complaints
  customError.customMethod4() // typescript complaints
}

EDITED:

Background is when you are compiling down to ES5, some inheritances cannot be compatible.

Is there a way I can cast it once and not have to use as everytime I use the variable?

So far the only way to work with it is:

const myCustomError = (customError as CustomError)

Open to other bright ideas.


Solution

  • Write an User-Defined Type Guard:

    function isCustomError(x: any): x is CustomError {
        return x.constructor === CustomError;
    }
    

    And use it:

    if (isCustomError(err)) {
        err.customMethod1();
    }
    

    See this playground.