How can I define the return type of a lodash reduce function with Typescript?
我正在尝试定义此Typescript函数的输出。
1 2 3 4 5 6 | function (data: { topicId: number; subTopicId: number; topicName: string; subTopicName; string; }[] ) { var output = <IAnything>{ dataMap: _.reduce(data, function (rv, v) { rv[v.subTopicId] = v; return rv; }, {}); |
我可以映射一些我未包括在此问题中的部分,但是我对如何制作dataMap字段感到困惑。有人可以帮助我,告诉我如何在下面的界面中映射lodash _.reduce的输出。从我可以看到,减少的输出是:
1 | data: { topicId: number; subTopicId: number; topicName: string; subTopicName; string; }[] |
但是我该如何表示以及如何表示用于数组索引的subTopicId?
1 2 3 4 | interface IAnything { //data: { id: number; name: string; }[]; dataMap: } |
这是dataMap输出的样子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "1":{"topicId":1, "subTopicId":1, "topicName":"x", "subTopicName":"x"}, "2":{"topicId":1, "subTopicId":2, "topicName":"x", "subTopicName":"x"}, "62":{"topicId":10, "subTopicId":62, "topicName":"x", "subTopicName":"x"} } |
您的界面应如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | interface IAnything { dataMap: IMap } interface IData { topicId: number; subTopicId: number; topicName: string; subTopicName; string; } interface IMap{ [key: string] : IData; } |
然后您的函数应如下所示:
1 2 3 4 5 6 7 8 9 | function (data: IData[]){ var output = <IAnything>{ dataMap: _.reduce(data, function (rv: IData, v: IData) { rv[v.subTopicId] = v; return rv; }, {}) }; } |