Ramda.js采用(键)类型与原生地图

时间:2017-05-23 11:36:53

标签: typescript types ramda.js pluck

说我有以下代码:

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
    }
]

1 个答案:

答案 0 :(得分:0)

从这开始:

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
   },{}));

就像这样,这对于Ramda来说更为惯用:

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) 

显然这可能会被清理一下,但我的代码基于your other question

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

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