3

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" }
    ]
});
user1167761
  • 345
  • 3
  • 15

2 Answers2

1

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" }
    ]
});
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
1

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" }
    ]
});
dmck
  • 7,801
  • 7
  • 43
  • 79