为什么 Flow 假设这个函数 returns 是一个 RegExp?

Why does Flow assume this function returns a RegExp?

我有以下代码:一个函数,其中 return 是数组中的一个选项。选项可以是字符串或正则表达式,return 值将随之而来。

const pick = (options: Array<string | RegExp>): string | RegExp =>
  options[Math.floor(Math.random() * options.length)];

const myOptions = ['hello', 'goodbye']
const randomId: string = pick(myOptions);

这引发了这个错误:

Cannot assign pick(...) to randomId because RegExp [1] is incompatible with string [2].Flow(incompatible-type)

这是为什么?

好的,根据评论构建,这里有几个问题:

  • 数组的类型签名是“字符串数组或正则表达式数组”,而不是“字符串数组或正则表达式数组”
  • Flow 不知道 return 类型与提供的类型相匹配,因此函数 return 可能是一个正则表达式,不能存储在字符串中。

使用泛型,我们可以像这样重新定义函数:

const pick = <T>(options: Array<T>): T =>
  options[Math.floor(Math.random() * options.length)];

这很好用。