当对多个类型使用 Or 时,类型上不存在属性

and*_*ins 9 javascript typescript angular

在我的 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;

The*_*bio 2

您面临的问题是 Angular 的模板类型检查似乎已启用。

启用相关设置后,视图中使用的对象类型将得到验证。如果该对象万一不具有其中一项属性,这些验证将导致您面临的错误。

具体来说,在您的情况下,因为接口UserProfileDetails没有视图中使用的某些属性,所以角度正在考虑使用businessIdbusinessLocation出现错误。

有一些选项可以修复它:

  • 禁用模板类型检查(我不建议这样做)
  • 使用变量的泛型类型profile(我也不喜欢这个)
  • 使用管道来转换视图中对象的类型。(我的偏好)
<div *ngIf="(profile | castProfileType)?.businessId">{{profile.businessId}}</div>
<div *ngIf="(profile | castProfileType)?.businessLocation">{{profile.businessLocation}}</div>
Run Code Online (Sandbox Code Playgroud)
@Pipe({
    name: 'castProfileType',
})
export class CastProfileTypePipe implements PipeTransform {
  transform(value: profileObject) {
    return Object.keys(value).includes('businessId') ? <BusinessProfileDetails>value : <UserProfileDetails>value
  }
}
Run Code Online (Sandbox Code Playgroud)