在我的 html 中,我使用一个函数来调用 getObjInfo(oBJ)
并且将对象传递给它。现在我的 getObjInfo 函数中有 switch 语句,用于返回基于 html 传递的 obj 类型的内容,它看起来像这样( Cars 、 People 、 Animals 是接口(interface)):
public getObjInfo(elem: Cars | People | Animals) {
switch (typeof(elem)) {
case 'Cars':
return elem.color;
case 'People':
return elem.age;
case 'Animals':
return elem.name;
}
}
这是传递它的 html:
<div class="list-bg" *ngFor="#obj of listToDisplay">
{{getObjInfo(obj)}}
</div>
我没有收到任何错误,它只是不起作用......我做错了什么......?
最佳答案
如果 Cars
、People
和 Animals
是接口(interface),那么您不能使用 typeof
来实现,因为这些接口(interface)仅在编译时存在,在运行时不存在。
您可以使用一个函数来检查elem
的属性并返回类型:
function getElementType(elem: Cars | People | Animals) {
if (elem.carProperty1 && elem.carProperty2) {
return "Cars";
}
if (elem.peopleProperty1 && elem.peopleProperty2) {
return "People";
}
if (elem.animalsProperty1 && elem.animalsProperty2) {
return "Animals";
}
return "unknown"
}
然后:
public getObjInfo(elem: Cars | People | Animals) {
switch (getElementType(elem)) {
case 'Cars':
return elem.color;
case 'People':
return elem.age;
case 'Animals':
return elem.name;
}
}
但是,如果您将这些接口(interface)转换为类,您将能够使用 instanceof
来实现。
关于angularjs - 无法根据 typeof 对象使用 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38683322/