javascript - 在 TypeScript 中扩展 Error 类时,接口(interface)不被应用

标签 javascript typescript

我有一个Exception1扩展 Error 的类JavaScript 类,除此之外它还实现了一个接口(interface) 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

最佳答案

当您扩展 ArrayErrorMap 等内置类型时,原型(prototype)链有点困惑,您可以需要显式修复,以便类中定义的成员可供类的实例使用。 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

关于javascript - 在 TypeScript 中扩展 Error 类时,接口(interface)不被应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49966806/

相关文章:

javascript - 如何为 chai-http 导出 node express 应用程序

typescript - 根据 typescript 中的构造函数参数重载类属性

Angular 7 Typescript - 服务错误处理丢失对象实例

javascript - 类型错误(参数 `content' 的预期哈希值(得到字符串)

javascript - 将数据从 SCORM 播放器发送到 LMS

Typescript 没有将 Object.entries 转译为 ES5

TypeScript:带有泛型的递归深度可变。错误:T 不可分配给 Mutable<T>

Angular 2 基本身份验证不起作用

javascript - 从后面的代码运行 JavaScript 代码到 updatePanel

javascript - 是否可以连接 Lua 和 javascript?