typescript 打字稿 lodash:如何声明与 _.map 一起使用的字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30269526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript lodash: How to declare a dictionary to use with _.map?
提问by Xavier John
How to declare a dictionary to use with _.map in lodash?
如何在 lodash 中声明与 _.map 一起使用的字典?
Here is the sample TypeScript program.
这是示例 TypeScript 程序。
<reference path="../scripts/typings/lodash/lodash.d.ts" />
interface IQuestionAndOptions {
text: string;
options: { [key: number]: string };
}
function sample() {
var question: IQuestionAndOptions = { text: "Are you happy?", options: {} };
question['1'] = "Yes";
question['2'] = "No";
var values = _.map(question.options, function (v: string, k: number) {
return { text: v, value: k }; });
}
It is not happy with the declaration of question.options and gives the following error.
它对 question.options 的声明不满意,并给出以下错误。
Argument of type '{ [key: number]: string; }' is not assignable to parameter of type 'List' at the _.map command
'{ [key: number]: string; 类型的参数 }' 不可分配给 _.map 命令中类型为“List”的参数
采纳答案by Xavier John
The issue was with the lodash.d.ts and updating it solved the issue.
问题出在 lodash.d.ts 上,更新它解决了这个问题。
nuget lodash.TypeScript.DefinitelyTyped version="0.3.8"
nuget lodash.TypeScript.DefinitelyTyped version="0.3.8"
uses
用途
map<T, TResult>(
collection: List<T>,
pluckValue: string): TResult[];
definition and works.
定义和作品。
回答by billc.cn
The map
method is defined as the following in DefinitelyTyped:
该map
方法在绝对类型中定义如下:
map<T, TResult>(
collection: Array<T>,
callback: ListIterator<T, TResult>,
thisArg?: any): TResult[];
It requires the collection
argument to be an array, which is more specific than { [key: number]: string }
. You have to declare the options
field as an array for it to work.
它要求collection
参数是一个数组,这比{ [key: number]: string }
. 您必须将该options
字段声明为数组才能使其工作。