【问题标题】:Inherited exceptions and instanceof继承的异常和instanceof
【发布时间】:2017-12-22 12:11:57
【问题描述】:
为什么这段代码返回false?
class MyException extends Error {
constructor(message: string) {
super(message);
}
}
const e = new MyException('blah');
console.log(e instanceof MyException); // returns 'false'
当我执行以下代码时不会发生:
class Base {
constructor(message: string) {
console.log(message);
}
}
class MyClass extends Base {
constructor(message: string) {
super(message);
}
}
const e = new MyClass('blah');
console.log(e instanceof MyClass); // returns 'true'
【问题讨论】:
标签:
typescript
inheritance
error-handling
instanceof
【解决方案1】:
这是一个已知问题:
instanceof is broken when class extends Error type 相关
使用 TypeScript 功能支持 Polymer 标准。
建议的解决方法是:
很遗憾,这是我们为了尝试采用
更符合标准的发射,以便我们可以使聚合物工作
使用 TypeScript。
对于背景,是 2.2 中的有意更改(请参阅 #12123 和
我们维基上的部分),但很难克服
汇编。我相信在#12790 中有一些对话
解决方法。
您现在可以采取的解决方法是创建一个中间类
可以扩展。
export interface MyErrorStatic {
new (message?: string): RxError;
}
export interface MyError extends Error {}
export const MyError: MyErrorStatic = function MyError(this: Error, message: string) {
const err = Error.call(this, message);
this.message = message;
this.stack = err.stack;
return err;
} as any;
export class HttpError extends MyError {
// ...
}
在 TypeScript 2.2 中,您将能够自行设置原型。
// Use this class to correct the prototype chain.
export class MyError extends Error {
__proto__: Error;
constructor(message?: string) {
const trueProto = new.target.prototype;
super(message);
// Alternatively use Object.setPrototypeOf if you have an ES6 environment.
this.__proto__ = trueProto;
}
}