【问题标题】:Flow: conditional function response typeFlow:条件函数响应类型
【发布时间】:2018-10-31 02:28:32
【问题描述】:

在流类型检查器中,如何根据参数对象属性定义函数响应类型。这是一个例子:

function test(argument) {
  if (argument.responseType === "string") {
    return "Some string value"
  }
  return { some: { json: "object" } };
}

是否可以在此代码中添加流类型?

我知道可以写:

declare export function test(argument: { responseType: string}): string | { some: { json: string } };

但这还不够。我不想要Union Type 回复。根据提供的参数,它必须是字符串或对象。

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    Flow 通过向同一函数提供several definitions 来允许函数重载。与literal types next 一起应该可以工作:

    declare function test(argument: {responseType: 'string'}): string;
    declare function test(argument: {}): {some: {json: string}};
    

    这是一个 Flow 尝试example code

    【讨论】:

    • @jmarceli 感谢您修复语法问题/添加示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 2019-06-23
    • 1970-01-01
    • 2020-11-10
    相关资源
    最近更新 更多