How to declare a dictionary to use with _.map in lodash?
Here is the sample TypeScript program.
<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.
Argument of type '{ [key: number]: string; }' is not assignable to parameter of type 'List' at the _.map command
The map
method is defined as the following in DefinitelyTyped:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With