Search code examples
typescriptenyo

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


How to declare an object with method that can take array of any objects?

In the code beloy: (1) code has a compile error 'Incompatible types in array'. (2) no error. I want to use (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" }
    ]
});

Solution

  • You can use any[] to accomplish this in your interface.

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