You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中判断可能为undefined的对象类型报错求助

解决方法

最简单的修复方式是利用逻辑与的短路特性,先判断this.animal是否存在,再执行属性检查,避免undefined报错:

export class SomeClass {
   public animal?: Dog | Cat;
   ...
   public isDog() {
    return this.animal && 'woof' in this.animal;
  }
}

如果想同时让TypeScript自动识别animal的类型(提供类型守卫能力),可以稍作调整,代码量依然很少:

export class SomeClass {
   public animal?: Dog | Cat;
   ...
   public isDog(): this.animal is Dog {
    return !!this.animal && 'woof' in this.animal;
  }
}

第一种写法已经能满足你的模板判断需求:当animal为undefined时,isDog()会返回false,模板会渲染catCardTemplate;如果需要区分undefined和Cat的场景,可再单独处理,但按当前逻辑已足够解决问题。

内容的提问来源于stack exchange,提问作者zappee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:13:11