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

Can a non-null assertion be combined with a ternary?

假设我想在 Angular 应用程序中使用 TypeScript 从我的路由中获取一个 'id' 参数。

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

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

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

或者它总是 return 第一个操作数(如果为空则失败)?

别忘了TS会被编译成JS,非空断言在JS中是不存在的。

所以你有两个解决方案:

  • 测试每一步

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

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