继承的异常和instanceof

问题描述 投票:2回答:1

为什么这段代码会返回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个回答
2
投票

这是一个已知问题:instanceof is broken when class extends Error type与使用TypeScript功能的Polymer标准支持相关。

建议的解决方法是:

  • 创建中介课
  • 设置原型

不幸的是,这是我们尝试采用更符合标准的发射所做的更改,以便我们可以启用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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.