Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the proper typescript types for addEventListener mousemove and it's event argument?

Question: Without using any, What is the proper typing for my onMouseMove function?

export class Main {
  private dTimer: number;

  constructor() {
    this.init();
  }

  private init() {
    this.mouseHandlers();
  }

  private mouseHandlers() {
    document.addEventListener('mousemove', this.onMouseMove)
  }

  private onMouseMove: EventListener = (event: MouseEvent) => {
    clearTimeout(this.dTimer);
    this.dTimer = setTimeout(() => {
      console.log(event.pageX, event.pageY)
    }, 500);
  }
}

Typescript is complaining about my types and I dunno how to make it happy w/o using any.

main.ts(38,3): error TS2322: Type '(event: MouseEvent) => void' is not assignable to type 'EventListener'.
  Types of parameters 'event' and 'evt' are incompatible.
    Type 'Event' is not assignable to type 'MouseEvent'.
      Property 'altKey' is missing in type 'Event'.
like image 525
Armeen Harwood Avatar asked Mar 11 '18 23:03

Armeen Harwood


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.

What is Mousemove event?

The mousemove event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it.

How often does the Mousemove event fire?

What is Mousemove event in Javascript? The mousemove event occurs whenever the mouse pointer moves within the selected element. The mousemove() method triggers the mousemove event, or attaches a function to run when a mousemove event occurs. Note: Each time a user moves the mouse one pixel, a mousemove event occurs.


1 Answers

What are the proper typescript types for addEventListener mousemove and it's event argument?

Being explicit will set you free:

onMouseMove: { (event: MouseEvent): void } = (event: MouseEvent) => {
}

Or, let TypeScript infer it from assignment 🌹:

onMouseMove = (event: MouseEvent) => {
}
like image 124
basarat Avatar answered Oct 16 '22 01:10

basarat