【问题标题】:Property "url" does not exit on type never?类型永远不存在属性“url”?
【发布时间】:2017-05-01 14:58:55
【问题描述】:

我需要订阅路由器事件: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
        });

为什么 typescript 不能将 event 识别为 NavigationStartNavigationEnd 的类型?虽然当我在“else if”中控制台“事件”时,我得到了“事件”的所有属性。

我见过this link1(对我不起作用)和this issue,人们给出了关闭这个问题的各种理由,design limitations。有没有我想要实现的解决方法,other than doing:

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

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

【问题讨论】:

  • 您尝试过将事件重命名为其他名称吗?
  • 是的,试过了!在subscribe 中取一个与我在filter 中使用的名称不同的名称。那是行不通的。有效的是,我在if block 之前创建了event 的别名,例如:let alias = event。在if condition 中使用event,在else if condition 中使用alias

标签: angular typescript


【解决方案1】:

这是 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) {

        }
});

【讨论】:

  • 好吧,我猜,any 一定会有所作为,即使是 angular 的人也会做类似的事情。谢谢,它有效:)
  • 顺便说一句,我猜打字稿不允许在函数之前写“函数”关键字。
  • 你可以在函数前使用function关键字。如果你在一个类中定义它,语法会有点不同。
  • 而且你甚至不必在类型保护中使用any。请参阅我的更新答案。
  • @sarvana,我在实施您的解决方案时犯了一些错误,我没有用 Navigation 类型替换 .subscribe((event: any)),但是现在当我替换它们时,它显示相同的错误,@987654334 @
猜你喜欢
  • 2017-08-15
  • 1970-01-01
  • 2012-11-09
  • 2016-02-22
  • 2021-01-09
  • 2021-07-10
  • 2022-01-07
  • 2022-01-27
相关资源
最近更新 更多