Home > Mobile >  Typing RxJs fromEvent's parameter as a MouseEvent yields error
Typing RxJs fromEvent's parameter as a MouseEvent yields error

Time:06-15

I'm trying to listen to a user's mouse click on a DOM element, and to fetch the event's clientX/clientY mouse coordinates. Using angular v12.1.5 and RxJs v6.6.0.

const click$ = () =>
fromEvent(document, 'click').pipe(
  map((ev: MouseEvent) => ev.clientX)
)

The code above yields the following error:

Argument of type 'OperatorFunction<MouseEvent, number>' is not assignable to parameter of type 'OperatorFunction<Event, number>'.
  Type 'Event' is missing the following properties from type 'MouseEvent': altKey, button, buttons, clientX, and 21 more.ts(2345)

I copy pasted the code above from the RxJs documentation for map, so I'm confused as to why this doesn't work. Is it a version issue?

CodePudding user response:

Well, the fromEvent function returns an object of type Event, while ev is supposed to by of type MouseEvent. One way of achieving the desired behavior would be to do something like:

const click$ = fromEvent(window, 'click').pipe(
    map((event: Event) => event as MouseEvent),
    map((mouseEvent: MouseEvent) => mouseEvent.clientX)
);
  • Related