8

I have the following piece of code:

 this.routerSubscription = this._router.events
     .filter(event => event instanceof NavigationStart)
     .subscribe((event:Event) => {
        ....
     });

Which throws me an error of:

error TS2345: Argument of type '(event: Event) => void' is not assignable to parameter of type 'NextObserver<NavigationStart | NavigationEnd | NavigationCancel | NavigationError> | ErrorObserve...'.
  Type '(event: Event) => void' is not assignable to type '(value: NavigationStart | NavigationEnd | NavigationCancel | NavigationError) => void'.
    Types of parameters 'event' and 'value' are incompatible.
      Type 'NavigationStart | NavigationEnd | NavigationCancel | NavigationError' is not assignable to type 'Event'.
        Type 'NavigationStart' is not assignable to type 'Event'.
          Property 'bubbles' is missing in type 'NavigationStart'.

What am I doing wrong?

uksz
  • 18,239
  • 30
  • 94
  • 161

2 Answers2

21

I guess you forgot about:

import { Event } from '@angular/router';

Or use it like:

import { Event as NavigationEvent } from '@angular/router';
...
.subscribe((event: NavigationEvent)

See also

Community
  • 1
  • 1
yurzui
  • 205,937
  • 32
  • 433
  • 399
1

In my case, the solution wasn't about importing the Event interface.
Instead, the key was to utilize a TypeScript type guard to explicitly inform the TypeScript compiler about the type of event once it passes through the filter function of RxJS.

using your code as an example:

 this.routerSubscription = this._router.events
     .filter((event) : event is NavigationStart => event instanceof NavigationStart)
     .subscribe((event) => {
        // Your logic here...
     });

Notice how we surrounded the event argument with parentheses and added the type guard ((event): event is NavigationStart).
This way, the Typescript compiler understands that if the arrow function returns true, event is guaranteed to be of type NavigationStart.
With the type guard in place, TypeScript will treat event as NavigationStart within the subscribe method.