以下代码以两种方式声明了字符串的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'
答案 0 :(得分: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')