流:条件函数响应类型

时间:2018-10-06 08:24:27

标签: javascript flowtype

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

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

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

我知道可以写:

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

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

1 个答案:

答案 0 :(得分:1)

Flow通过向同一函数提供several definitions来允许函数重载。下一个应该与literal types一起使用:

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

这是Flow试用example code