Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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 --global
typings 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);

Using Typescript 2.0, you can import underscore with the import statement like below:

import * as _ from "underscore";

Then, call any underscore function using _.<function_name>.

PS: don't forget to install underscore library with npm for example.

Update 2021

Add the following dependencies to package.json:

  "dependencies": {
    "underscore": "^1.13.1"
  },
  "devDependencies": {
    "@types/underscore": "^1.11.3"
  }

Then run:

$ npm install

In your TypeScript files, import underscore using:

import * as _ from 'underscore';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top