javascript - FlowJS 内联柯里化(Currying)函数类型与 Union

标签 javascript types flowtype

如何在 Flow 中使用 Union 编写内联柯里化(Currying)函数类型?

以下示例可以正常工作:

type Foo = () => () => string;

function func(foo: Foo): string {
    return foo()();
}

这是 Union 的问题:

type Foo = () => string | () => () => string;

function func(foo: Foo): string {
    const f = foo();
    if (typeof f === 'function') {
      return f(); // Cannot return `f()` because function type [1] is incompatible with string [2].
    }
    return f;
}

但是,它可以通过以下方式修复:

type TF = () => string;
type Foo = TF | () => TF;

function func(foo: Foo): string {
    const f = foo();
    if (typeof f === 'function') {
      return f();
    }
    return f;
}

那么如何使用 Union 编写内联柯里化(Currying)函数类型呢?

Try Flow

最佳答案

问题出在这里:

type Foo = () => string | () => () => string;

目前,这表示 Foo 是一个函数类型,其返回类型为:

string | () => () => string

这不是你想要的。如果添加一些括号,Flow 将正确理解这一点:

type Foo = (() => string) | () => () => string;

(Try Flow)

关于javascript - FlowJS 内联柯里化(Currying)函数类型与 Union,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56017655/

相关文章:

javascript - tr 的背景颜色不会使用 jquery 改变

javascript - Highcharts setState() 上的 3D 渲染问题

javascript - 使用 $(this) 对象获取 DropDownList 的选定项目

字符串 - Python 3.5 需要写一个类似字节的对象,而不是 'str'

reactjs - 在 Jest 测试文件中使用流会导致未定义的测试、期望等

javascript - 无法使用 Nodejs 将元数据添加到 strip 客户订阅创建中?

c# - 处理引用类型

c++ - 在 C++ 中捕获类型错误

javascript - 在 webpack 构建后保留 Flow 类型

javascript - 流类型注释: why `ClassName<{}>` ?