javascript - 流式返回函数时不保留泛型函数参数

标签 javascript flowtype

在我的代码中,我想返回一个高阶函数并将我的参数类型传递给返回函数。最小的简化代码如下所示。

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/

相关文章:

javascript - FlowJS 类型以及使用 && 和赋值

javascript - Flow Type高阶组件(HOC)props类型保存

javascript - 如何从 React Native javascript 语法切换到 es6

javascript - 如何在 React.CreateClass 中为对象属性提供流类型提示

javascript - 无法在 flow-js 中将类型设置为 Array<string>

javascript - 子 react 元素的流类型注释

javascript - 如何在html中使用javascript删除基本标签?

javascript - 打印图表时避免出现工具提示

javascript - jQuery 语法荧光笔不工作

javascript - 如何在 Google Maps InfoWindow 中创建 CSS 样式的 dom 元素?