英文:
check the type of an Angular object that can be undefined as well
问题
我正在学习Angular,我想编写一个方法,如果对象的类型是`Dog`(它具有`woof`属性),则返回`true`。
到目前为止,我有以下内容:
export class SomeClass {
public animal?: Dog | Cat;
...
public isDog() {
return 'woof' in this.animal; <-- 对象可能为 'undefined'
}
}
然后根据对象的类型显示内容的方式如下:
<div *ngIf="isDog(); then dogCardTemplate else catCardTemplate"></div>
我的问题是`this.animal`可能为未定义,并出现以下错误:
对象可能为 'undefined'。
请问您是否能帮助我以尽可能少的代码行数简单解决这个问题?
英文:
I am learning Angular and I would like to write a method that returns true
if the type of the object is Dog
(it has a woof
property).
This is what I have so far:
export class SomeClass {
public animal?: Dog | Cat;
...
public isDog() {
return 'woof' in this.animal; <-- Object is possibly 'undefined'
}
}
Then I show the content based on the type of the object this way:
<div *ngIf="isDog(); then dogCardTemplate else catCardTemplate"></div>
My problem is that this.animal
can be undefined and the following error appears:
Object is possibly 'undefined'.
Could you please help me to solve this in a simple way with as less code line as possible?
答案1
得分: 0
以下是翻译好的部分:
export class SomeClass {
public animal?: Dog | Cat;
public isDog() {
return this.animal // 首先检查是否已定义
&& 'woof' in this.animal; // 稍后检查动物类型
}
}
为什么?
因为属性是可选的,我们需要检查它是否已定义,只有在那之后才能检查它是否是一只狗。
注意:如果您想检查它是否是一只猫,您需要重复未定义的检查。
英文:
The proper way to check if is the following:
export class SomeClass {
public animal?: Dog | Cat;
public isDog() {
return this.animal // check to see if its defined first
&& 'woof' in this.animal; // animal type check later
}
}
Why?
Well since the property is optional, we need to make a check to see if it is defined and only after that can we make a check for if its a dog.
Note: if you want to check that it is a cat, you will need to repeat the undefined check.
答案2
得分: 0
我建议你不要直接在HTML中使用'get'方法。然后,如果你百分之百确定这个动物不会是undefined,?可以被移除。
public animal: Dog | Cat;
或者可以参考IDK4real的答案。
英文:
i sugest you to not use directly 'get' method on html https://stackoverflow.com/questions/55051164/using-setters-and-getter-variables-on-html-angular-component
Then if you are 100% sure this animal cannot be undefined, ? can be removed
public animal: Dog | Cat;
Or follow the IDK4real answer
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论