在下面的代码块中,当存在OuterY
函数时,OuterZ
和getInnerValues
类型定义上仅 会发生流错误。
错误表明"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
答案 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