打字稿。数组中不兼容的类型。如何使用可以获取任何对象数组的方法声明对象?

时间:2013-04-03 15:31:20

标签: typescript enyo

如何使用可以获取任何对象数组的方法声明对象?

在代码beloy中:(1)代码有一个编译错误'数组中的不兼容类型'。 (2)没有错误。我想用(1)。

declare var enyo;


// (1). compile error: 'Incompatible types in array'

enyo.kind({
    name: "HelloWidget",
    components: [
        { name: "hello", content: "Hello From Enyo" },
        { kind: "Button", content: "Click Me!", ontap: "helloTap" }
    ]
});


// (2). no erros but have to write <any>

enyo.kind({
    name: "HelloWidget",
    components: [
        <any>{ name: "hello", content: "Hello From Enyo" },
        <any>{ kind: "Button", content: "Click Me!", ontap: "helloTap" }
    ]
});

2 个答案:

答案 0 :(得分:1)

最好的解决方法是在enyo上提供一些类型信息,以便编译器可以将上下文类型应用于数组表达式:

interface EnyoComponent {
    name?: string;
    content?: string;
    kind?: string;
    ontap?: string;
}

declare var enyo: {
    kind(settings: {
        name: string;
        components: EnyoComponent[];
    });
};

enyo.kind({
    name: "HelloWidget",
    components: [
        { name: "hello", content: "Hello From Enyo" },
        { kind: "Button", content: "Click Me!", ontap: "helloTap" }
    ]
});

答案 1 :(得分:1)

您可以使用any[]在您的界面中完成此操作。

declare var enyo: {
    kind(settings: {
        name: string;
        components: any[];
    });
};

// The following will now compile without errors

enyo.kind({
    name: "HelloWidget",
    components: [
        { name: "hello", content: "Hello From Enyo" },
        { kind: "Button", content: "Click Me!", ontap: "helloTap" }
    ]
});