gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:41:16 28 4
gpt4 key购买 nike

如何声明字典以在 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”的参数

最佳答案

map方法在DefinitelyTyped中定义如下:

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

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

关于 typescript lodash : How to declare a dictionary to use with _. map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30269526/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com