【发布时间】: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 <filename>.js吗?在这种情况下,您不会从中获得任何有趣的东西,但它可以派上用场。 -
如果 Flow 允许用户为这种用例提供类型级函数,那就太酷了。
-
@Alan,感谢Nuclide,我最近开始使用
flow suggest,它很整洁。我同意用户提供的功能会非常有趣。对于类似的用例,人们还可以关注$PropertyType 和 $Values(如果有的话)的可能演变。
标签: javascript types annotations flowtype