Typescript lodash:如何声明要与 _.map 一起使用的字典?
Typescript lodash: How to declare a dictionary to use with _.map?
如何在 lodash 中声明与 _.map 一起使用的字典?
这是示例 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 }; });
}
对question.options的声明不满意,报了下面的错误。
类型为'{ [key: number]: string; }' 不能在 _.map 命令
中分配给 'List' 类型的参数
map
方法在DefinitelyTyped中定义如下:
map<T, TResult>(
collection: Array<T>,
callback: ListIterator<T, TResult>,
thisArg?: any): TResult[];
要求collection
参数为数组,比{ [key: number]: string }
更具体。您必须将 options
字段声明为数组才能工作。
问题出在 lodash.d.ts 上,更新它解决了问题。
nuget lodash.TypeScript.DefinitelyTyped 版本="0.3.8"
使用
map<T, TResult>(
collection: List<T>,
pluckValue: string): TResult[];
定义和作品。
如何在 lodash 中声明与 _.map 一起使用的字典?
这是示例 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 }; });
}
对question.options的声明不满意,报了下面的错误。
类型为'{ [key: number]: string; }' 不能在 _.map 命令
中分配给 'List' 类型的参数map
方法在DefinitelyTyped中定义如下:
map<T, TResult>(
collection: Array<T>,
callback: ListIterator<T, TResult>,
thisArg?: any): TResult[];
要求collection
参数为数组,比{ [key: number]: string }
更具体。您必须将 options
字段声明为数组才能工作。
问题出在 lodash.d.ts 上,更新它解决了问题。
nuget lodash.TypeScript.DefinitelyTyped 版本="0.3.8"
使用
map<T, TResult>(
collection: List<T>,
pluckValue: string): TResult[];
定义和作品。