在我的 Angular 组件中,我Input将提供 2 种类型中的一种。
@Input() profile: UserProfileDetails | BusinessProfileDetails;
Run Code Online (Sandbox Code Playgroud)
配置文件模板很简单,我只想使用单个模板,因此我不会重复代码。但由于类型的属性不同,我收到了模板错误。
export interface UserProfileDetails {
createdOn: Date;
id: string;
name: string;
}
Run Code Online (Sandbox Code Playgroud)
export interface BusinessProfileDetails {
businessId: string;
businessLocation: string;
createdOn: Date;
id: string;
name: string;
}
Run Code Online (Sandbox Code Playgroud)
以及我的模板中的代码:
<div>
<h1>{{profile.name}}</h1>
<div>{{profile.createdOn}}</div>
<div>{{profile.id}}</div>
<div *ngIf="profile?.businessId">{{profile.businessId}}</div>
<div *ngIf="profile?.businessLocation">{{profile.businessLocation}}</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我相信我明白为什么会收到错误,但我不确定如何在仍然使用该or条件的情况下解决问题@Input() profile: UserProfileDetails | BusinessProfileDetails;