【问题标题】:Can I write Flow type annotations for this function reducing an array of objects to an object我可以为此函数编写流类型注释,将对象数组减少为一个对象吗
【发布时间】:2017-06-05 04:08:10
【问题描述】:

以下代码以两种方式声明字符串的 Flowtype Union。 1) 使用内置的Union Type,但需要再次输入所有代码,造成重复。 2)利用$Keys:Flow v0.38.0正确推断makeObjectWithKeys类型,但我想知道是否可以手动编写此类注释。

const codesArray = [
   {
     name: 'Lorem',
     code: 'lm'
   },
   {
     name: 'Ipsum',
     code: 'ip'
   },
   // ...
 ]

// Define the CodeType "manually" with the Union built-in
type CodeTypeManual =
   | "lm"
   | "ip"
   // ...

const noErrorManual: CodeTypeManual = 'lm'
const flowErrorPropertyNotFoundManual: CodeTypeManual = 'zz'

// Define the CodeType by taking advantage of $Keys
const makeObjectWithKeys = (inArray) => { // Type annotations?
  return inArray.reduce(
        (objAcc, curObj) => { // Type annotations?
          const retObj = { ...objAcc }
          const { code } = curObj
          retObj[code] = code
          return retObj
        }
        , {}
  )
}
const objectWithCodesAsKeys = makeObjectWithKeys(codesArray)

type CodeType = $Keys<typeof objectWithCodesAsKeys>

let noError: CodeType = 'ip'
let flowErrorPropertyNotFound: CodeType = 'zz'

【问题讨论】:

  • 嗯,有趣的例子——我没有意识到 Flow 可以推断出这些类型。至于你的问题,这个没有回答,但是你用过flow suggest &lt;filename&gt;.js吗?在这种情况下,您不会从中获得任何有趣的东西,但它可以派上用场。
  • 如果 Flow 允许用户为这种用例提供​​类型级函数,那就太酷了。
  • @Alan,感谢Nuclide,我最近开始使用flow suggest,它很整洁。我同意用户提供的功能会非常有趣。对于类似的用例,人们还可以关注$PropertyType 和 $Values(如果有的话)的可能演变。

标签: javascript types annotations flowtype


【解决方案1】:

如果我正确理解您的问题,以下内容可能会有所帮助。

/* @flow */
const codesArray = [
   {
     name: 'Lorem',
     code: 'lm'
   },
   {
     name: 'Ipsum',
     code: 'ip'
   },
   // ...
 ]

const makeObjectWithKeys = function<T: Object>(inArray: Array<T>, key: $Keys<T>) {
  return inArray.reduce((objAcc: { [name: typeof key]: T }, curObj: T) => {
    return Object.assign({}, objAcc, { [curObj[key]]: curObj })
  }, {})
}

const objectWithCodesAsKeys = makeObjectWithKeys(codesArray, 'code')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多