代码之家  ›  专栏  ›  技术社区  ›  user2167582

如何将变量强制转换为特定类型以使typescript相信everywhere?

  •  0
  • user2167582  · 技术社区  · 5 年前

    由于IE的原因,我需要构建一个自定义错误,但是,尽我所能,必须用构造函数检查错误。

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

    现在我怎样才能在if语句中说服typescript呢?

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

    后台是指当您向下编译到ES5时,某些继承无法兼容。

    有没有一种方法我可以投一次而不用用 as 每次我用这个变量?

    const myCustomError = (customError as CustomError)
    

    对其他好主意持开放态度。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Shalom Peles    5 年前

    写一篇 User-Defined Type Guard :

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

    并使用它:

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

    看到这个了吗 playground