Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript addEventListener set event type

Tags:

People also ask

What is the type of event in TypeScript?

Events supported are: AnimationEvent , ChangeEvent , ClipboardEvent , CompositionEvent , DragEvent , FocusEvent , FormEvent , KeyboardEvent , MouseEvent , PointerEvent , TouchEvent , TransitionEvent , WheelEvent . As well as SyntheticEvent , for all other events.


I'm trying to do this

document.addEventListener('click', (e: MouseEvent) => { ...

However, Typescript cannot know the exact event type based on event name.

'click' => MouseEvent

and thinks the type of e is of type Event. As is in definition

declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
    
interface EventListener {
    (evt: Event): void;
}
    
interface EventListenerObject {
    handleEvent(evt: Event): void;
}

It obviously complains

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 tell Typescript the e is of type MouseEvent? Or if I asked more generally: how to type addEventListener properly?