angular - 如何在模板中的类型上显示具有属性的对象不存在
问题描述
我有类型的对象WithBalance | WithoutBalance
withBalance : { balance:number, name:string } withoutBalance : { name : string}
<span>{{object?.balance ?? 0}} </span>
但是当我尝试这样做时,我得到了错误Property 'balance' does not exist on type WithoutBalance
。
如何解决这个问题呢?
解决方案
可选链接 ( ?.
) 让我们编写代码,如果遇到 null 或 undefined,TypeScript 可以立即停止运行某些表达式。因此,在您的情况下,您使用object?.balance
了这意味着 if object
is not null 尝试访问该balance
属性。因此,如果 object 在withoutBalance
type 中,则会引发如下错误:Property 'balance' does not exist on type WithoutBalance
.
in
您可以像这样在组件中使用运算符:
getBalance (){
if ("balance" in this.object) {
return this.object.balance
}
return 0;
}
<span>
{{ getBalance()}}
</span>
推荐阅读
- python-3.x - Pandas 数据框转置列名而不是索引
- python - 如果组中的任何一行包含某个值,则创建一个新列并分配值
- c# - 如何在 C# 7.0 中使用 CodeContracts?
- terraform - 什么时候在 terraform 中定义变量?
- php - 如何使用 Ionic 4、mysql 和 Angular 7 进行身份验证和 Crud 操作?
- neo4j - iMac 上 Neo4j Desktop 的 config 文件夹和 bin 文件夹在哪里?
- tensorflow - Keras 中基于 F1/AUC 时期的指标
- spring - 未找到 c3p0 hsqldb 驱动程序类
- node.js - 如何将元数据添加到 mac/linux 上的文件夹
- mysql - 创建 Mysql 表