在我的 Angular 組件中,我Input將提供 2 種型別中的 1 種。
@Input() profile: UserProfileDetails | BusinessProfileDetails;
組態檔模板很簡單,我只想使用單個模板,所以我不重復代碼。但是由于型別的屬性不同,我收到了一個模板錯誤。
export interface UserProfileDetails {
createdOn: Date;
id: string;
name: string;
}
export interface BusinessProfileDetails {
businessId: string;
businessLocation: string;
createdOn: Date;
id: string;
name: string;
}
以及我模板中的代碼:
<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>
我相信我理解我收到錯誤的原因,但我不確定如何在仍然使用or條件的同時解決問題@Input() profile: UserProfileDetails | BusinessProfileDetails;
uj5u.com熱心網友回復:
這不是真的,or盡管您會這樣描述它;union不直觀地,它在 TypeScript 中被稱為型別
基本上,您只能參考兩個介面共有的屬性|
嘗試使用交叉&型別
uj5u.com熱心網友回復:
profile您可以使用檢查using運算子的屬性的功能來設定解決方法in。不是最好的解決方案,但您可以根據需要保持介面聯合:
零件
getValue(
attribut: string,
obj: UserProfileDetails | BusinessProfileDetails
): any {
if (attribut in obj) {
return obj[attribut];
}
}
模板
<div>
<h1>{{ profile.name }}</h1>
<div>{{ profile.createdOn }}</div>
<div>{{ profile.id }}</div>
<div>{{ getValue('businessId', profile) }}</div> <!-- can be improved using a check method combined with ngIf -->
<div>{{ getValue('businessLocation', profile) }}</div>
</div>
uj5u.com熱心網友回復:
您面臨的問題是 Angular 的模板型別檢查似乎已啟用。
啟用相關設定后,將驗證視圖中使用的物件型別。如果該物件有任何可能沒有屬性之一,這些驗證將導致您面臨的錯誤。
特別是在您的情況下,因為該界面UserProfileDetails沒有視圖中使用的某些屬性,因此角度正在考慮使用businessId或businessLocation錯誤。
有一些選項可以修復它:
- 禁用模板型別檢查(我不建議這樣做)
- 對變數使用泛型型別
profile(我也不喜歡這個) - 使用管道在視圖中轉換物件的型別。(我的偏好)
<div *ngIf="(profile | castProfileType)?.businessId">{{profile.businessId}}</div>
<div *ngIf="(profile | castProfileType)?.businessLocation">{{profile.businessLocation}}</div>
@Pipe({
name: 'castProfileType',
})
export class CastProfileTypePipe implements PipeTransform {
transform(value: profileObject) {
return Object.keys(value).includes('businessId') ? <BusinessProfileDetails>value : <UserProfileDetails>value
}
}
uj5u.com熱心網友回復:
您也可以嘗試:
<div *ngIf="profile.hasOwnProperty('businessId')">{{profile.businessId}}</div>
<div *ngIf="profile.hasOwnProperty('businessLocation')">{{profile.businessLocation}}</div>
uj5u.com熱心網友回復:
轉到tsconfig檔案并更改嚴格模式(如果我沒記錯的話,第 8 行)到false
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/437355.html
標籤:javascript 有角度的 打字稿
下一篇:在ngoninit中使用異步管道
