由于 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)
接受其他聪明的想法。
最佳答案
function isCustomError(x: any): x is CustomError {
return x.constructor === CustomError;
}
并使用它:
if (isCustomError(err)) {
err.customMethod1();
}
查看此playground .
关于javascript - 如何将变量转换为特定类型以使 typescript 无处不在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59997190/