Does the "url" property ever go out of type?
I need to subscribe to router events: NavigationStart
andNavigationEnd
this._router.events
.filter(event => event instanceof NavigationStart || event instanceof NavigationEnd)
.subscribe((event: NavigationStart | NavigationEnd) => {
if (event instanceof NavigationStart) {
// event.url, typescript does not flag any error
}
else if (event instanceof NavigationEnd) {
// typescript flags, that property "url" does not exist on type "never".
// if I make this block as the only block,
// i.e. remove the previous "if" block and put this under "if"
// then it works fine
}
// event.url, works fine, even here
});
Why doesn't typescript recognize it event
as a type NavigationStart
or NavigationEnd
? Although when I console the "event" inside the "else if" I get all the properties of the "event".
I saw this ssylku1 (did not work for me) and this problem , people have given different reasons for the closure of this issue design limitations
. Is there a workaround that I want to achieve,other than doing:
.subscribe((event: any) => {})
EDIT: Implementation of @ Saravana's solution
source to share
This is an open issue with the TypeScript compiler. See https://github.com/Microsoft/TypeScript/issues/11664
A possible workaround in your case you can flip the condition to check first NavigationEnd
. Since it NavigationEnd
contains all properties NavigationStart
, the compiler assumes that all instances NavigationEnd
are instances NavigationStart
:
this._router.events
.filter(event => event instanceof NavigationStart || event instanceof NavigationEnd)
.subscribe((event: NavigationStart | NavigationEnd) => {
if (event instanceof NavigationEnd) {
}
else if (event instanceof NavigationStart) {
}
});
source to share