Typescript lodash: How to declare a dictionary to use with _.map?

Xavier John picture Xavier John · May 16, 2015 · Viewed 18.3k times · Source

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

Answer

billc.cn picture billc.cn · May 16, 2015

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.