I'm attempting to accomplish this
document.addEventListener('click', (e: MouseEvent) => { ...
However, Typescript is unable to determine the precise event type based on the event name.
'click'
=> MouseEvent
and considers the type of e
to be Event
. As per the definition provided
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface EventListener {
(evt: Event): void;
}
interface EventListenerObject {
handleEvent(evt: Event): void;
}
This obviously leads to an error message
TS2345: Argument of type '(e: MouseEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'. Type '(e: MouseEvent) > void' is not assignable to type 'EventListener'. Types of parameters 'e' and 'evt' are incompatible. Type 'Event' is missing the following properties from type 'MouseEvent': altKey, button, buttons, clientX, and 25 more.
How can I inform Typescript that e
is indeed of type MouseEvent
? Or more broadly, how can I correctly type addEventListener
?