Declared Index Signature Overloads

Topics: General, Language Specification
Dec 20, 2012 at 11:19 PM

I need to declare an interface that accepts both string and number indexes for interfacing w/ an external JS environment (I know it seems strange) and a class that implements that interface. E.g.:

declare interface MyInterface {
    [index: string]: any;
    [index: number]: any;
}

declare class MyClass implements MyInterface {
    [index: string]: any;
    [index: number]: any;
}
This doesn't compile and it also doesn't if I remove the signatures from the declared class. If I only had one index signature in the interface, I could remove it from the class declaration and all is well. Is this something that can be supported?

Dec 20, 2012 at 11:54 PM

I just ran into this as well.  I needed to define an interface containing a property with two different possible types and this isn't currently allowed. Given that this is a fairly common scenario in JavaScript I think the team should consider supporting this.

 

-steve  

Dec 21, 2012 at 12:43 AM

+1 from me also - I ran into this a few days ago with some code that consumed input field definitions (where the 'value' field could be either string or bool).

Dec 28, 2012 at 7:24 PM

Thanks.  I'll copy this to an issue for tracking.  As for if you are just declaring (rather than implementing) the class, you can do as we do for the types in lib.d.ts, namely:

declare interface MyInterface {
    [index: string]: Date;
    [index: number]: Event;
    test(): number;
}

declare var MyClass: {
    new (): MyInterface;
}

var x = new MyClass();
var m1 = x["test"]; // m1 is of type Date
var m2 = x[5];      // m2 is of type Event
x.test();

Dec 28, 2012 at 7:24 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.