3

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

在代码中:(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" }
    ]
});
4

2 回答 2

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" }
    ]
});
于 2013-04-03T16:14:27.767 回答
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" }
    ]
});
于 2013-04-03T20:52:05.740 回答