TypeScript - 使用Array Literal初始化必需属性时转换为对象

时间:2015-05-14 23:23:45

标签: casting typescript

我正在尝试初始化一个具有对象文字的接口类型的对象:

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。

1 个答案:

答案 0 :(得分:0)

export interface LocalizableObject {
    label?: string;
    localizedLabels: LocalizedLabel[];
    description?: string;

    // Not an array type, did you mean LocalizedDescription[] ?
    localizedDescriptions: LocalizedDescription;
}