从TypeType中的Error中断`instanceof`检查中继承 [英] Inherit from Error breaks `instanceof` check in TypeScript
问题描述
有人可以解释一下为什么下面代码的error instanceof CustomError
部分是false
吗?
Can someone explain me why the error instanceof CustomError
part of below code is false
?
class CustomError extends Error {}
const error = new CustomError();
console.log(error instanceof Error); // true
console.log(error instanceof CustomError); // false ???
class ParentClass {}
class ChildClass extends ParentClass { }
const child = new ChildClass();
console.log(child instanceof ParentClass); // true
console.log(child instanceof ChildClass); // true
关于Error对象,有什么特别之处吗?我想制作自己的错误类型以供检查.
Is something special about Error object? I would like to make my own error types that i can check against.
顺便说一句,我已经在最新的 TypeScript游乐场
Btw i've checked the above code on latest TypeScript Playground
推荐答案
此处.
Turns out an change has been introduced in TypeScript@2.1 that breaks this pattern. The whole breaking change is described here.
通常来说,朝这个方向前进似乎太复杂/错误了.
In general it seems it's too complicated/error to even go with this direction.
拥有自己的错误对象并保留某些原始Error
作为属性可能更好:
Probably better to have own error object and keeps some original Error
as an property:
class CustomError {
originalError: Error;
constructor(originalError?: Error) {
if (originalError) {
this.originalError = originalError
}
}
}
class SpecificError extends CustomError {}
const error = new SpecificError(new Error('test'));
console.log(error instanceof CustomError); // true
console.log(error instanceof SpecificError); // true
这篇关于从TypeType中的Error中断`instanceof`检查中继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!