flowtype - 带有联合参数的函数间接导致联合成员出现莫名其妙的错误
问题描述
在下面的代码块中,流错误仅在函数存在时发生在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);
为什么会这样?
解决方案
Flow 没有意识到对于所有可能的情况都存在inner
类型属性。解决此问题的一种方法是键入函数以接受具有预期类型的对象:{value: string}
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
函数以接受通用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<T> = {
inner: Array<Inner<T>>
}
// no errors
const getInnerValues = <T>(outer: Outer<T>) => outer.inner.map(inner => inner.value);
推荐阅读
- reactjs - 未从减速器返回状态时出现神秘的 TypeScript 错误消息
- javascript - Ag-grid 自定义工具提示不适用于网格单元
- python - ValueError:尝试相对导入超出顶级包 - 导入文件时
- spring - 如何编写 Bamboo 构建脚本来调用 REST 端点
- angular - NativeScript TabView 中的徽章
- regex - 括号中的正则表达式
- r - 如何在 Shiny 中保存反应值?
- c# - 通过 Nlog C# 在单元测试中检查日志消息
- python-3.x - 使用 Paramiko 的基本 SSH 连接失败
- javascript - 当 React Jest 测试失败时,输出挂载的 DOM 的 HTML 的最佳方式是什么?