PLB
PLB

Reputation: 891

Error in IDE (VScode) on a RxJS subscribe call with a typed parameter

I'm trying out some RxJS functions in Angular and copied some code from a tutorial (link). My project is configured in 'strict' mode. The app is simply logging the coordinates of a click in the console (I did a Stackblitz: link)

Both locally and on Stackblitz the app works BUT locally my IDE is displaying an error. On line 25 of AppComponent, within the subscribe, onClick is underlined and I get "No overload matches this call". The problem seems to be related to the type definition MouseEvent on line 12. If I change it to any, the error disappears.

My assumptions are:

  1. the code works, because upon transpiling TS to JS, the typization is lost (so effectively it's like if I did have any in my final call)
  2. Stackblitz does not show an error, because its constraints-checks are not as efficient as the ones from VScode

My questions:

Upvotes: 0

Views: 123

Answers (1)

Mike Jerred
Mike Jerred

Reputation: 10525

You can do it like this:

const eventListener = <K extends keyof DocumentEventMap>(type: K) => 
  bindCallback<K, DocumentEventMap[K]>(document.addEventListener)(type);

Stackblitz: https://stackblitz.com/edit/angular-ivy-pzxguu?file=src/app/app.component.ts

You could also use fromEvent from rxjs instead:

import { fromEvent } from 'rxjs';

...

fromEvent(document, 'click').subscribe(...);

Upvotes: 1

Related Questions