[英]TypeScript - Casting to Object When Initializing Required Property with an Array Literal
我正在嘗試初始化具有接口類型和對象文字的對象:
return {
id: 0,
name: name,
localizedLabels: [
{localeCd: defaultLocaleCd, label: name}
],
localizedDescriptions: [],
useForNetworkBuild: false,
temporalSplitting: false,
compounds: [],
primaryElements: [],
defaultMapIcon: null,
defaultRegularIcon: null,
markerColor: null,
nodeShape: null
};
對象的類型是我創建的稱為Entity的接口。 它有幾個父接口。 引起該問題的一個原因是LocalizableObject的“ localizedDescriptions”屬性(對深層次結構表示抱歉):
export interface Entity extends hubBase.PersistableObject,
hubLocalization.LocalizableObject,
hubBase.GraphicallyDisplayable {
name: string;
useForNetworkBuild: boolean;
temporalSplitting: boolean;
compounds: Compound[];
primaryElements: Element[];
}
export interface LocalizedLabel extends hubBase.PersistableObject {
localeCd: string
label: string;
}
export interface LocalizedDescription extends hubBase.PersistableObject {
localeCd: string
description: string;
}
export interface LocalizableObject {
label?: string;
localizedLabels: LocalizedLabel[];
description?: string;
localizedDescriptions: LocalizedDescription;
}
編譯器出現錯誤,提示“ localCd”屬性不可用,並抱怨“ []
localizedDescriptions []
初始化方法:
我試圖將整個對象文字轉換為Entity
。 我還嘗試在“ localizedDescriptions”的賦值中的[]
之前添加強制類型轉換。 錯誤仍然存在。 有沒有一種方法可以投射此屬性以消除此錯誤?
我正在使用TypeScript 1.4.1。
export interface LocalizableObject {
label?: string;
localizedLabels: LocalizedLabel[];
description?: string;
// Not an array type, did you mean LocalizedDescription[] ?
localizedDescriptions: LocalizedDescription;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.