Flow说下面voidnullify
返回的类型是不兼容的。我想我错过了什么?
import faker from 'faker'
type P =
| string
| number
| boolean
function voidnullify(func: () => P): ?P {
const random: number = faker.random.number({
min: 1,
max: 10
})
const result = func()
if (random <= 7) return result
else if (random <= 9) return null
else return undefined
}
function someBoolean() {
return true
}
function someString() {
return "hello"
}
function someNumber() {
return 1
}
let maybeNum: ?number
let maybeStr: ?string
let maybeBool: ?boolean
maybeNum = voidnullify(someNumber)
maybeStr = voidnullify(someString)
maybeBool = voidnullify(someBoolean)
答案 0 :(得分:1)
我认为你正在按照你尝试的方式做的事情是不受支持的。我不确定 是否应该工作,但是当你试图保护输入类型(它看起来像?)时,在Flow中执行此操作的正确方法是有界多态+通用参数:
type P =
| string
| number
| boolean
function voidnullify<A: P>(func: () => A): ?A {
const random: number = faker.random.number({
min: 1,
max: 10
})
...