[英]Property “url” does not exit on type never?
我需要訂閱路由器事件: NavigationStart
和NavigationEnd
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
});
為什么打字稿不能將event
識別為NavigationStart
或NavigationEnd
的類型? 雖然當我在“else if”中控制“事件”時,我獲得了“事件”的所有屬性。
我已經看到這個link1 (對我不起作用)和這個問題 ,人們已經給出了解決這個問題的各種原因, design limitations
。 other than doing:
什么之外,是否有我希望實現的解決方法other than doing:
.subscribe((event: any) => {})
編輯: @ Saravana解決方案的實施
這是TypeScript編譯器的一個開放問題。 請參閱https://github.com/Microsoft/TypeScript/issues/11664
在您的情況下可以解決方法,您可以先翻轉條件以檢查NavigationEnd
。 由於NavigationEnd
包含的所有屬性NavigationStart
,編譯器認為的所有實例NavigationEnd
是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) {
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.