Mou*_*iri 2 typescript angular
我有一个带有联合类型属性的接口:
interface Challenge {
id: number;
category: Category | string;
}
Run Code Online (Sandbox Code Playgroud)
分类界面:
Interface Category {
id: number;
label: string;
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,我有一个this.challengewhich type Challenge。
现在我想从模板中展示challenge.category.label:
<p>{{ challenge.category.label }}</p>
Run Code Online (Sandbox Code Playgroud)
但它不起作用,因为该label属性在字符串类型上不存在,并且如果我尝试从控制器访问该属性,则会出现相同的错误:
getLabel(): string {
return this.challenge.category.label
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能指定这个类别实例的类型是Category,因为模板直接偏好
您可以使用类型保护
最简单的解决方案是:
function getLabel(): string {
return (<Category>this.challenge.category).label;
}
Run Code Online (Sandbox Code Playgroud)
但如果你要多次使用它,那么创建一个类型保护是值得的:
function getLabel(): string {
if (isCategory(challenge.category)) {
return this.challenge.category.label;
} else {
// this will be string
return this.challenge.category;
}
}
function isCategory(category: Category | string): category is Category {
return (<Category>this.challenge.category).label !== undefined;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2844 次 |
| 最近记录: |