如何在正确推断键类型的同时过滤/减少键入的对象?例如:
/* @flow */
type A = {
a0?: string,
a1?: boolean,
a2?: number
}
type B = {
b0?: string,
b1?: boolean,
b2?: number
}
type AB = A & B
const keysA = ['a0', 'a1', 'a2']
// Given an AB object, keep only the keys that belong in type A
function keepA(ab: AB):A {
return keysA
.filter(prop => ab.hasOwnProperty(prop))
.reduce((obj, prop) => {
obj[prop] = ab[prop]
return obj
}, {} )
}
function flowTest(ab: AB) {
const a = keepA(ab)
return a
}
这会引发错误:
obj[prop] = ab[prop]
^ Cannot return `keysA.filter(...).reduce(...)`
because boolean [1] is incompatible with
string [2] in property `a0`.
References:
4: a1?: boolean,
^ [1]
3: a0?: string,
^ [2]
在任务obj[prop] = ab[prop]
中,流程似乎认为右侧可能是string | boolean | number
中的任何一个。
这是在flow.org/try上:
我对Flow来说还很陌生(通常是类型检查)。