typescriptunderscore.jsdefinitelytyped

How to use underscore lib from DefinitelyTyped with typescript?


DefinitelyTyped has provided a underscore declaration file, which defines a List interface, and used it heavily in the code.

// Common interface between Arrays and jQuery objects
interface List {
    [index: number]: any;
    length: number;
}

interface UnderscoreStatic {
    sortBy(list: List, iterator?: any, context?: any): any;
    groupBy(list: List, iterator: any): any;
    countBy(list: List, iterator: any): any;
}

I'm trying to use the countBy function:

// <reference path="../DefinitelyTyped/underscore/underscore.d.ts" />

declare var _: UnderscoreStatic;

_.countBy([1,2,3], function(item) {
    return item%2;
});

When I compile the file, it throws error:

> tsc commons.ts

> E:/commons.ts(5,0): Supplied parameters do not match any signature of call target:
    Could not apply type 'List' to argument 1, which is of type 'number[]'

I don't know why this error happened, since number[] fit the interface List.

Where is wrong, and how to fix it?


Solution

  • You need to pass an object compatible with the List interface, which is an array with a length:

    /// <reference path="underscore.d.ts" />
    
    var list: List;
    list[0] = 1;
    list[1] = 2;
    list[2] = 3;
    list.length = 3;
    
    _.countBy(list, function (item) {
        return item % 2;
    });
    

    In all honesty, an array technically fulfils this as it has a length property - but the above code compiles.

    The shorthand version of this is a bit nasty:

    /// <reference path="underscore.d.ts" />
    
    var list = <List><any> [1, 2, 3];
    
    _.countBy(list, function (item) {
        return item % 2;
    });