简体   繁体   English

如何将变量转换为特定类型以说服打字稿无处不在?

[英]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.出于 IE 的原因,我需要构建一个自定义错误,但是,尽我所能,必须使用构造函数检查错误。

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

Now how can I convince typescript that in an if statement?现在我怎样才能在 if 语句中说服打字稿呢?

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.背景是当你编译到 ES5 时,一些继承是不兼容的。

Is there a way I can cast it once and not have to use as everytime I use the variable?有没有一种方法可以让我投了一次,没有使用as ,每次我使用变量?

So far the only way to work with it is:到目前为止,使用它的唯一方法是:

const myCustomError = (customError as CustomError)

Open to other bright ideas.对其他聪明的想法持开放态度。

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 .看到这个游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM