【问题标题】:How to get an element from object of type predicate in Typescript Angular如何从 Typescript Angular 中的谓词类型对象中获取元素
【发布时间】:2019-01-14 08:19:06
【问题描述】:

希望这是有道理的,但我试图了解如何获取存在于特定类型对象上但被定义为类型谓词的元素。

即Team定义为

let team$: Observable<ErrorModel | Team>

所以成功调用这个 observable 的结果是类型 Team,它有一个 code,而 ErrorModel 没有,因此打字稿 linter 说 code does not exist on type ErrorModel | Team

基本上

return team$.subscribe(response => {
    console.log(response.code);
}

在这种情况下我该怎么说response.code - 即使我做一个typeof,它仍然会给我那个lint错误。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    由于结果可以是Team 或ErrorModel,编译器将只允许您访问两者的共同属性。您可以使用类型保护来缩小response 的类型。在这种情况下,in 类型保护:

    team$.subscribe(response => {
      if ('code' in response) console.log(response.code);
    });
    

    【讨论】:

      猜你喜欢
      • 2020-01-27
      • 2019-12-01
      • 2020-09-17
      • 1970-01-01
      • 2020-01-05
      • 2018-08-15
      • 2022-01-27
      • 2013-10-24
      • 1970-01-01
      相关资源
      最近更新 更多