Reputation: 657
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
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
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
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