16

In Angular 11 this works:

this.r.events.pipe(
    filter(event => event instanceof NavigationEnd),
    map((event: NavigationEnd) => event.url == ROUTES.APPLICATION))

However in Angular 12 it produces the error:

Argument of type 'MonoTypeOperatorFunction<Event_2>' is not assignable to parameter of type 'OperatorFunction<Event_2, NavigationEnd>'.
Type 'Observable<Event_2>' is not assignable to type 'Observable'.
Type 'Event_2' is not assignable to type 'NavigationEnd'.
Property 'urlAfterRedirects' is missing in type 'RouterEvent' but required in type 'NavigationEnd'.ts(2345)

Any ideas on how to fix this?

This question has the answer as adding:

"paths": {
    "rxjs": [
      "node_modules/rxjs"
    ],
    "rxjs/*": [
      "node_modules/rxjs/*"
    ]
}

To tsconfig.json. However that did not work ...

0

2 Answers 2

21

Update: Did a Google, this looks promising. Looks like a compact form of the type predicate I mentioned below. (Source)

filter((event): event is NavigationEnd => event instanceof NavigationEnd))

It would be really helpful to know the initial type of the event argument in .filter(event => event instanceof NavigationEnd)

Do you have a TypeScript plugin installed in your IDE? In VSCode and Atom, at least, plugins can show the types of variables in-line as you write your code. That would help you track down where the mismatch is.

If event => event instanceof NavigationEnd isn't sufficient to stop TS from barfing on the next line's type assertion (event: NavigationEnd), then maybe a type predicate would help?

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

1 Comment

The error is produced by compiling Angular using the CLI ... It worked fine in Angular 11 ... The event instance is some event that the router produces ... so ... it should be pretty straight forward ... Famous last words :)
3

I found this very frustrating.

The fix for me was making sure that Event was imported from @angular/router. The linting doesn't suggest that the lack of Event import is the error but it certainly fixes things:

import { Event, NavigationEnd, Router } from '@angular/router'

# NB notice declaration of event as type Event below
filter((event: Event): event is NavigationEnd => event instanceof NavigationEnd))

this makes it work for all router events too:

router.events.pipe(
  filter((event: Event): event is RouterEvent =>
    event instanceof RouterEvent
  )
)

1 Comment

In my case - VS Code 'quick actions' lead me to import 'filter' from the incorrect package (lodash). Glad I caught this after only 10 mins :')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.