Toast
Toast

Reputation: 657

Is it possible to extend the built-in Event class in TypeScript?

Code:

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

var event = new MyEvent("mousemove");

Runtime error:

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

Is there a way around this?

Upvotes: 2

Views: 5476

Answers (3)

dzwonu
dzwonu

Reputation: 117

You can create a static class which will be events provider:

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 });
    }
}

Upvotes: 0

basarat
basarat

Reputation: 275819

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

The issue is with the Event definition inside the v8 runtime. it doesn't lend itself to class based extension. The same issue used to exist for error, i.e. the following used to fail:

class MyError extends Error {
    constructor(message) {
        super(message);
    }
}

const error = new MyError("some message");

So at the moment. You cannot extend the Event class in TypeScript (or ES6 classes).

Upvotes: 5

yelsayed
yelsayed

Reputation: 5532

Event is not defined as a Class in Typescript since it's a JS object. What you want in this case is a wrapper class that calls Event's methods the way you want. You can then extend that wrapper.

Upvotes: 0

Related Questions