Can I define an Interface that can hold an object or an array?

Topics: General, Language Specification
Apr 17, 2013 at 10:44 PM
Edited Apr 17, 2013 at 10:46 PM
I am trying to define an interface that can hold an object or an array. For example, a tree where internal nodes are arrays and leaf nodes are objects could have a traversal function that takes a single argument which is an array or an object. To walk the tree the traversal function might test the argument and if an object (no length property) then process the leaf else call traverse on each element of the array.

I expected (hoped?) this would work:
interface ILeafOrNode {
    [node?: number] : ILeafOrNode;
    leaf?: string;

function Foo() {
    var root0: ILeafOrNode = { leaf: "leaf" };
    var root1: ILeafOrNode = [{ leaf: "left leaf", leaf: "right leaf" }];
I actually got warnings for both lines in Foo:

Error 1 Cannot convert '{ leaf: string; }' to 'ILeafOrNode': Index signatures of types '{ leaf: string; }' and 'ILeafOrNode' are incompatible: Call signature expects 0 or fewer parameters

Error 2 Cannot convert '{ leaf: string; }[]' to 'ILeafOrNode'

I also don't grok the messages in the error. So if that behavior is expected please help me to understand what the error message is telling me about the TypeScript type system.

Apr 23, 2013 at 2:11 AM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.