【问题标题】:Interface not being applied when Error class is extended in TypeScript [duplicate]在 TypeScript 中扩展 Error 类时未应用接口 [重复]
【发布时间】:2018-04-22 14:04:30
【问题描述】:

我有一个 Exception1 类,它扩展了 JavaScript 的 Error 类,同时它还实现了一个接口 SampleInterface

interface SampleInterface {
    func(): string;
}

class SampleClass {
    public message: string;

    constructor(message: string) {
        this.message = message;
    }
}

class Exception1 extends Error implements SampleInterface  {
    constructor(message: string) {
        super(message);
    }

    public func(): string {
        return "Exception1"
    }
}

在控制台中执行console.log(new Exception1('a').func()) 时出现此错误

Uncaught TypeError: (intermediate value).func is not a function
    at <anonymous>:1:33

但是,例如,如果该类扩展了其他一些类,这将按预期工作

class Exception2 extends SampleClass implements SampleInterface  {
    constructor(message: string) {
        super(message);
    }

    public func(): string {
        return "Exception2"
    }
}

在执行 console.log(new Exception2('a').func()) 时,我得到了预期的输出 Exception2

【问题讨论】:

标签: javascript typescript


【解决方案1】:

当你扩展像ArrayErrorMap这样的内置类型时,原型链有点混乱,你需要明确地修复它,以便你的类中定义的成员变得可用到你的类的实例。 TypeScript docu 中指出了这一点。

因此,为了解决此问题,您需要执行以下操作:

interface SampleInterface {
    func(): string;
}

class Exception1 extends Error implements SampleInterface  {
    constructor(message: string) {
        super(message);

        // Explicitly fix the prototype chain
        Object.setPrototypeOf(this, Exception1.prototype);
    }

    public func(): string {
        return "Exception1"
    }
}

console.log(new Exception1('a').func()) // and now it works

【讨论】:

    猜你喜欢
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 2021-05-05
    • 2018-09-23
    • 2020-06-09
    • 2020-04-09
    • 2021-08-07
    相关资源
    最近更新 更多