【问题标题】:Typescript lodash: How to declare a dictionary to use with _.map?Typescript lodash:如何声明要与 _.map 一起使用的字典?
【发布时间】:2015-07-27 23:16:30
【问题描述】:

如何在 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”类型的参数

【问题讨论】:

    标签: typescript lodash typescript1.4


    【解决方案1】:

    map方法在DefiniteTyped中定义如下:

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

    它要求collection 参数是一个数组,它比{ [key: number]: string } 更具体。您必须将 options 字段声明为数组才能使其工作。

    【讨论】:

      【解决方案2】:

      问题在于 lodash.d.ts,更新它解决了问题。

      nuget lodash.TypeScript.DefinitelyTyped version="0.3.8"

      用途

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

      定义和工作原理。

      【讨论】:

        猜你喜欢
        • 2020-02-03
        • 2017-12-24
        • 2019-02-03
        • 2017-09-25
        • 1970-01-01
        • 2021-08-17
        • 1970-01-01
        • 2013-03-30
        • 1970-01-01
        相关资源
        最近更新 更多