9

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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.