首页 > 解决方案 > 如何在模板中的类型上显示具有属性的对象不存在

问题描述

我有类型的对象WithBalance | WithoutBalance

withBalance : { balance:number, name:string } withoutBalance : { name : string}


<span>{{object?.balance ?? 0}} </span>

但是当我尝试这样做时,我得到了错误Property 'balance' does not exist on type WithoutBalance

如何解决这个问题呢?

标签: angulartypescript

解决方案


可选链接 ( ?.) 让我们编写代码,如果遇到 null 或 undefined,TypeScript 可以立即停止运行某些表达式。因此,在您的情况下,您使用object?.balance了这意味着 if objectis not null 尝试访问该balance属性。因此,如果 object 在withoutBalancetype 中,则会引发如下错误:Property 'balance' does not exist on type WithoutBalance.

in您可以像这样在组件中使用运算符:

getBalance (){
    if ("balance" in this.object) {
      return this.object.balance
    }
    return 0;
  }

<span>
  {{ getBalance()}}
</span>

推荐阅读