属性“url”不会退出类型永远不会?

时间:2017-05-01 14:58:56

标签: angular typescript

我需要订阅路由器事件:NavigationStartNavigationEnd

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识别为NavigationStartNavigationEnd?虽然当我在“else if”中控制“event”时,我获得了“event”的所有属性。

我看到this link1(对我不起作用)和this issue,人们已经提出了解决此问题的各种理由design limitations。是否有针对我想要实现的目标的解决方法other than doing:

.subscribe((event: any) => {})
  

编辑: @ Saravana解决方案的实施

enter image description here

1 个答案:

答案 0 :(得分:1)

这是TypeScript编译器的一个开放性问题。见https://github.com/Microsoft/TypeScript/issues/11664

在您的情况下可以解决方法,您可以先翻转条件以检查resultMsg。由于NavigationEnd包含NavigationEnd的所有属性,因此编译器认为NavigationStart的所有实例都是NavigationEnd个实例:

NavigationStart