非空断言可以与三元组合吗?

时间:2019-03-19 14:19:29

标签: angular typescript operators

让我们假设我想使用TypeScript在Angular应用程序中从路由中获取“ id”参数。

我可以做这样的事情:this!.route!.snapshot!.parent!.paramMap.get('id')

但是,如果我的断言是错误的,并且链的一部分返回null,那么这将在运行时引发异常。

那么做这样的事情有意义吗? this!.route!.snapshot!.parent!.paramMap.get('id') ? this!.route!.snapshot!.parent!.paramMap.get('id') : '-1'

还是总是返回第一个操作数(如果为空,则失败)?

1 个答案:

答案 0 :(得分:0)

不要忘记TS将被编译为JS,并且在JS中不存在非null断言。

因此,您有两种解决方案:

  • 测试每个步骤

    x = this && this.route && this.route.snapshot && ... || '-1'
    
  • 使用try catch块

    try {
      x = this.route.snapshot.parent.paramMap.get('id');
    } catch(error) {
      x = '-1';
    }
    
相关问题