繁体   English   中英

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

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

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

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

现在我怎样才能在 if 语句中说服打字稿呢?

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)

对其他聪明的想法持开放态度。

编写用户定义的类型保护

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

并使用它:

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

看到这个游乐场

暂无
暂无

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

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