How to use underscore lib from DefinitelyTyped with typescript? How to use underscore lib from DefinitelyTyped with typescript? typescript typescript

How to use underscore lib from DefinitelyTyped with typescript?


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;});


Check that the underscore TypeScript definition file matches the version of underscore you're using. The signature of countBy has changed and if the TS definition didn't match the underlying JS you'd get some unexpected behaviour.


First add underscore typing:

npm install typings --globaltypings install dt~jasmine --save --global

Then reference this file in your .ts source

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

Then import underscore to avoid compilation errors (be careful - underscore lib in this case should be installed as npm reference, not bower: npm install underscore --save)

import _ = require('underscore');

Then use underscore as usual using "_" global variable

_.isNumber(123);