在我的代码中,我想返回一个高阶函数并将我的参数类型传递给返回函数。最小的简化代码如下所示。
function curry<A, B: A>(a: A): (b: B) => void {
return () => {}
}
curry(123)("123") // expected error but not
我想知道为什么B
没有流向返回函数。似乎返回函数的类型为 (b: any) => void
。
我知道在这个示例中我可以更改绑定(bind)到签名的类型,例如 (a: A) => (b: A) => void
。但是我的真实场景比较复杂,需要一个幻像类型作为绑定(bind),就像上面的B
。
那么问题来了,B
实例化成什么类型?我可以使类型参数流向返回函数的参数位置吗?参数位置的类型会影响实际参数的类型推断吗?
最佳答案
返回的函数的类型为 (b: string) => void
正如您在运行 type-at-pos
命令时看到的
// @flow
function curry<A, B: A>(a: A): (b: B) => void {
return () => {}
}
const f = curry(123)
f("123")
运行 flow type-at-pos index.js 7 7
你会得到:
(b: string) => void
请记住,由于类型推断的工作方式,类型 A
(以及 B
)将相应地更改为以下调用
const f = curry(123) // <= f now has type (b: string | boolean) => void
f("123")
f(true)
关于javascript - 流式返回函数时不保留泛型函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39875492/