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
相关产品推荐
相关产品推荐

