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

StackOverflow https://stackoverflow.com/questions/15791672

  •  01-04-2022
  •  | 
  •  

Question

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" }
    ]
});
Was it helpful?

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

OTHER TIPS

The best fix would be to provide some type information on enyo so the compiler can apply a contextual type to the array expression:

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" }
    ]
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top