【问题标题】:Is it possible to extend the built-in Event class in TypeScript?是否可以扩展 TypeScript 中的内置 Event 类?
【发布时间】:2018-08-08 18:29:23
【问题描述】:

代码:

class MyEvent extends Event {
    constructor(name) {
        super(name);
    }
}

var event = new MyEvent("mousemove");

运行时错误:

Uncaught TypeError: Failed to constructor 'Event': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

有没有办法解决这个问题?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    Uncaught TypeError: Failed to constructor 'Event': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

    问题在于 v8 运行时中的 Event 定义。它不适用于基于class 的扩展。曾经存在相同的错误问题,即以下曾经失败:

    class MyError extends Error {
        constructor(message) {
            super(message);
        }
    }
    
    const error = new MyError("some message");
    

    所以现在。您不能在 TypeScript(或 ES6 类)中扩展 Event 类。

    【讨论】:

    【解决方案2】:

    您可以创建一个静态类作为事件提供者:

    static class EventProvider {
    
        static createEvent(name: string): Event {
            return new Event(name);
        }
    
        static createCustomEvent<T>(name: string, detail: T): CustomEvent<T> {
            return new CustomEvent<T>(name, { detail: detail });
        }
    }
    

    【讨论】:

      【解决方案3】:

      Event 在 Typescript 中没有定义为 Class,因为它是一个 JS 对象。在这种情况下,您想要的是一个包装类,它以您想要的方式调用Event 的方法。然后,您可以扩展该包装器。

      【讨论】:

      • Event is not defined as a Class in Typescript since it's a JS object 这不是用户遇到的限制。 Event 是用 new 签名定义的,它允许在 TypeScript 中继承(类似于 Error)。看我的回答?
      猜你喜欢
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2012-03-12
      • 1970-01-01
      相关资源
      最近更新 更多