Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 614
Xavier John Avatar asked May 15 '15 22:05

Xavier John


1 Answers

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.

like image 177
billc.cn Avatar answered Sep 25 '22 08:09

billc.cn