带有联合参数的函数间接导致联合成员发生无法解释的错误

时间:2018-07-07 02:39:40

标签: flowtype

在下面的代码块中,当存在OuterY函数时,OuterZgetInnerValues类型定义上仅 会发生流错误。

错误表明"Y""Z""X"不兼容。例如:“字符串文字Y与字符串文字X不兼容。”

/* @flow */

type Inner<T> = { value: T };

type OuterX = { inner: Array<Inner<"X">> };
type OuterY = { inner: Array<Inner<"Y">> };
type OuterZ = { inner: Array<Inner<"Z">> };

type Outer = OuterX | OuterY | OuterZ;

// If the next line is present, errors occur on
// lines 6 and 7 complaining that "Y" and "Z" are
// incompatible with "X". When the next line is
// commented out, the errors go away. Why??
const getInnerValues = (outer: Outer) => outer.inner.map(inner => inner.value);

为什么会这样?

Click here to see the issue on flow.org/try

Click here to see the same issue with stricter typing on flow.org/try

1 个答案:

答案 0 :(得分:0)

Flow并未意识到在inner的所有可能情况下都存在类型为{value: string}的{​​{1}}属性。解决此问题的一种方法是键入函数以接受具有预期类型的​​对象:

Try

Outer

执行此操作的另一种方法(可能是更好的方法)是将/* @flow */ type Inner<T> = { value: T }; type OuterX = { inner: Array<Inner<"X">> }; type OuterY = { inner: Array<Inner<"Y">> }; type OuterZ = { inner: Array<Inner<"Z">> }; type Outer = OuterX | OuterY | OuterZ; // no errors const getInnerValues = (outer: {inner: Array<{value: string}>}) => outer.inner.map(inner => inner.value); 重新定义为接受类型参数的类型。然后,您可以通用地键入Outer函数来接受通用getInnerValues实例:

Try

Outer