Array Type and the List Interface

Topics: General, Language Specification
Feb 22, 2013 at 9:28 PM
Edited Feb 22, 2013 at 9:30 PM
Hi, why is this producing error and how can you define a variable that can accept arrays and JQuery objects?
    interface List {
        [index: number]: any;
        length: number;
    }

    var jQueryObject = $(document);
    var arrayObject = [1, 2, 3];
    var a: List = jQueryObject; // OK
    var b: List = arrayObject;  // Error: Cannot convert 'number[]' to 'List'
Feb 23, 2013 at 12:36 AM
I can't tell what you are trying to do, but my best guess is this.
interface List {
        index: any[];
        length: number;
    }

    var jQueryObject = $(document);
    var arrayObject = {index: [1, 2, 3],length: 3};
    var a: List = jQueryObject; // OK
    var b: List = arrayObject;  // Error: Cannot convert 'number[]' to 'List'
Feb 23, 2013 at 4:41 PM
I think the OP is trying to create an interface that is 'implemented' by the pre-existing typed arrays. Unfortunately OP, it's a bug still waiting to be fixed. You'll have to come up with a workaround until then.

http://stackoverflow.com/questions/13074851/possible-to-define-indexer-interface-for-number
http://typescript.codeplex.com/workitem/331
Mar 5, 2013 at 4:06 AM
Edited Mar 7, 2013 at 9:49 PM
Yes, like GJK said, I'm trying to create an interface that is common between arrays and jQuery objects, so that we can use that interface as type of method parameters in Underscore definitions. The current workaround is to just overload the methods, but it creates a lot of duplication:
// Common interface between Arrays and jQuery objects (not?)
interface List {
    [index: number]: any;
    length: number;
}

interface UnderscoreStatic {
    //...

    forEach(list: List, iterator: ObjectIterator, context?: any): any[];
    forEach(object: any, iterator: ListIterator, context?: any): any[];

    //...
}