Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将变量强制转换为特定类型以使typescript相信everwhere?_Javascript_Typescript_Ecmascript 5_Custom Errors - Fatal编程技术网

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

Javascript 如何将变量强制转换为特定类型以使typescript相信everwhere?,javascript,typescript,ecmascript-5,custom-errors,Javascript,Typescript,Ecmascript 5,Custom Errors,出于IE的原因,我需要构建一个自定义错误,但是,尽我所能,必须使用构造函数检查错误 customError instanceof CustomError; // false customError.constructor === CustomError; // true 现在我如何在if语句中说服typescript呢 if (customError.constructor === CustomError) { customError.customMethod1() // typescri

出于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)
向其他聪明的想法敞开心扉。

写一篇:

并使用它:

if (isCustomError(err)) {
    err.customMethod1();
}
见此。

写一篇:

并使用它:

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

参见此图。

您将强制转换与构造函数/实例比较相结合。你是在试着投下什么还是比较什么
instanceof
是您想要进行比较的内容。您可以将
{}用作T
{}
@mwilson-TypeScript将自动缩小条件语句中的
customError
类型。OP并不是在尝试进行强制转换,而是在询问是否有办法让TypeScript在必须使用
.constructor
comparison@mwilson当传输到ES5时不是这样。您可以共享创建customError的位置吗?您将强制转换与构造函数/实例比较混合在一起。你是在试着投下什么还是比较什么
instanceof
是您想要进行比较的内容。您可以将
{}用作T
{}
@mwilson-TypeScript将自动缩小条件语句中的
customError
类型。OP并不是在尝试进行强制转换,而是在询问是否有办法让TypeScript在必须使用
.constructor
comparison@mwilson传输到ES5时不会。您可以共享创建customError的位吗?