根据变量的类型调用不同的函数时,正确的 Flow 类型模式是什么?

What's the correct Flow type pattern when calling different functions depending on the type of a variable?

我是 Flow 的新手,从 javascript 中的 "do whatever you like with the code" 样式更改为更严格的输入 Flow 有时会让您感到痛苦。

我有一个 class 函数返回以下内容:

const { id: idParam, params } = this.config[tag];
return params.map((param: string | ObjectConfigParam) => {
  const paramType = typeof param;
  let ret = { id: element.id, tag, position };
  if (paramType === 'string') {
    ret = { ...ret, ...this.resolveStringParam(element, param) };
  } else if (paramType === 'object') {
    ret = { ...ret, ...this.resolveObjectParam(element, param) };
  }
  return ret;
})

因为 params 可以是两种不同的东西(简单的 string 或更复杂的 ObjectConfigParam),我定义了不同的函数来处理它们。函数的签名是:

resolveStringParam(element: any, param: string): Field

resolveObjectParam(element: any, param: ObjectConfigParam): Field

运行流量检查器报如下错误: Cannot call this.resolveStringParam with param bound to param because ObjectConfigParam [1] is incompatible with string [2]. 对于第一个电话和 Cannot call this.resolveObjectParam with param bound to param because string [1] is incompatible with ObjectConfigParam [2]. 第二个。

您需要将 typeof param 放在 if 条件中。 顺便说一句,你不需要第二个 if.

https://flow.org/try/#0PQKgBAAgZgNg9gdzCYAoVAXAngBwKZgDyARgFZ4DGGAwnAHZQCWA5gAoCGATuwLZgC8YAN5gAznB54AauxgBXPAC4xGTozrMwAXwDc6VFDl0qjemE55xMAG54AyqvVsuvABSjVyj2o0BKYVoGRiZmFla2JORUHNw8rnBkypGUNPRMzrH+QoGoFPQeYAAeAmCuOC48Xo4aYAA+RGQptAwsMbz+-AB8wqhgYIxQpdj4cIPlsQL8ggDk3k7TWb195pZwNvbVGW7j7Xp9WmB4MKIEQkt9YWsRjdEVZRW+e9qoWkA

type ObjectConfigParam = { someValue: string };

function resolveStringParam(str: string) {}
function resolveObjectParam(obj: ObjectConfigParam) {}

const x = (param: string | ObjectConfigParam) => {
  if (typeof param === 'string') {
    resolveStringParam(param);
  } else {
    resolveObjectParam(param);
  }
}