繁体   English   中英

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

[英]TypeScript. incompatible types in array. How to declare an object with method that can take array of any objects?

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

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

最好的解决方法是提供关于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" }
    ]
});

您可以使用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" }
    ]
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM