3

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?

3 Answers 3

5

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the link @DavidSherret
0

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.

1 Comment

Event is not defined as a Class in Typescript since it's a JS object this is not the limitation the user is hitting. Event is defined with new signatures which allows inheritance in TypeScript (similar to Error). See my answer 🌹
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.