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

How to declare a dictionary for use with _.map in lodash?

Here is an example 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 }; }); } 

Unhappy with the question.options declaration and gives the following error.

An argument of type '{[key: number]: string; } 'is not assigned to the parameter of the "List" type in the _.map command

+6
source share
2 answers

The problem was with lodash.d.ts and updated, and the problem was resolved.

nuget lodash.TypeScript.DefinitelyTyped version = "0.3.8"

uses

 map<T, TResult>( collection: List<T>, pluckValue: string): TResult[]; 

and working.

0
source

The map method is defined as Defined:

  map<T, TResult>( collection: Array<T>, callback: ListIterator<T, TResult>, thisArg?: any): TResult[]; 

The collection argument requires an array that is more specific than { [key: number]: string } . You must declare the options field as an array for it to work.

0
source

Source: https://habr.com/ru/post/987309/


All Articles