拉姆达.js拔(键)类型与原生地图



假设我有以下代码:

const results = //some complex datastructure generated by a third party api call
const reducedList = results.map((item) => item.awesome_key)
.map((awesomeKeyList) => awesomeKeyList
.reduce((memo, awesomeKey) => {//stuff},{})))

此代码的工作方式类似于一个超级按钮。现在假设我决定通过采摘将Ramda用于第一张地图,如下所示:

import R from Ramda;
R.pluck('awesome_key', results)
.map((awesomeKeyList) => awesomeKeyList
.reduce((memo, awesomeKey) => {},{})))

这将失败,并显示:

Property 'reduce' does not exist on type '{}'.

Ramda.pluck上的类型是:

pluck<T>(p: string|number, list: any[]): T[];
pluck(p: string|number): <T>(list: any[]) => T[];

这些类型会阻止我以这种方式使用 reduce?

示例(简化)结构:

things: [
{
awesome_key: [{
long_name: 'string',
short_name: 'string',
types: {
0: 'string from set',
1?: 'string'
}
}]
other_fields not relevant here
}
]

从这个开始:

const results = [
{
awesome_key: [{
long_name: 'foo',
short_name: 'bar',
types: {
0: 'abc',
1: 'def',
2: 'ghi'
}
}, {
long_name: 'baz',
short_name: 'qux',
types: {
0: 'pqr',
1: 'xyz'
}
}],
other_fields: 'not relevant here'
}
]
const interestingTypes = ['pqr', 'xyz'];

据我所知,这两个都有相同的行为:

results.map((item) => item.awesome_key)
.map((addressComponentList) => addressComponentList.reduce((memo, addressComponent) => {
if (interestingTypes.indexOf(addressComponent.types[0]) !== -1) {
if (!memo[addressComponent.types[0]]) {
memo[addressComponent.types[0]] = addressComponent.long_name
}  
}
return memo
},{}));
R.pluck('awesome_key', results)
.map((addressComponentList) => addressComponentList.reduce((memo, addressComponent) => {
if (interestingTypes.indexOf(addressComponent.types[0]) !== -1) {
if (!memo[addressComponent.types[0]]) {
memo[addressComponent.types[0]] = addressComponent.long_name
}  
}
return memo
},{}));

就像这个一样,这对拉姆达来说更

习惯一些:
R.pipe(
R.pluck('awesome_key'),
R.map(reduce((memo, addressComponent) => {
if (interestingTypes.indexOf(addressComponent.types[0]) !== -1) {
if (!memo[addressComponent.types[0]]) {
memo[addressComponent.types[0]] = addressComponent.long_name
}  
}
return memo
},{}))
)(results) 

显然,这也可能被清理一下,但我的代码是基于你的另一个问题。

pluck('field', xs)确实应该返回与xs.map(x => x.field)相同的值。

您列出的打字稿签名不是我认为pluck,它被记录为:: k -> [{k: v}] -> [v],这意味着它接受(字符串)键和包含该键的对象列表,返回值列表

相关内容

最新更新