Fre*_*ind 10 typescript definitelytyped
DefinitelyTyped提供了一个下划线声明文件,它定义了一个List接口,并在代码中大量使用它.
// 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;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用该countBy功能:
// <reference path="../DefinitelyTyped/underscore/underscore.d.ts" />
declare var _: UnderscoreStatic;
_.countBy([1,2,3], function(item) {
return item%2;
});
Run Code Online (Sandbox Code Playgroud)
当我编译该文件时,它会抛出错误:
> 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[]'
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会发生这个错误,因为number[]适合界面List.
错在哪里,以及如何解决?
您需要传递与List接口兼容的对象,该接口是一个长度为的数组:
/// <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;
});
Run Code Online (Sandbox Code Playgroud)
老实说,数组技术上满足了它,因为它有一个长度属性 - 但上面的代码编译.
这个简写版有点讨厌:
/// <reference path="underscore.d.ts" />
var list = <List><any> [1, 2, 3];
_.countBy(list, function (item) {
return item % 2;
});
Run Code Online (Sandbox Code Playgroud)