javascript - Flow 不允许我将 `Array` 传递给 `Array `(子类型数组到超类型数组)
问题描述
我有一个类型的值Array<A>
(一个子类型数组)。Flow 不允许我将它传递到期望的位置Array<A | B>
(超类型数组),即使它显然有效。
例如,我不能将具有类型的值分配给Array<'left' | 'right'>
类型为Array<string>
:
const directions: Array<'left' | 'right'> = ['right', 'left'];
const messages: Array<string> = directions; // error
引发此错误:
2: const messages: Array<string> = directions; // error
^ Cannot assign `directions` to `messages` because in array element: Either string [1] is incompatible with string literal `left` [2]. Or string [1] is incompatible with string literal `right` [3].
References:
2: const messages: Array<string> = directions; // error
^ [1]
1: const directions: Array<'left' | 'right'> = ['right', 'left'];
^ [2]
1: const directions: Array<'left' | 'right'> = ['right', 'left'];
^ [3]
同样,我不能将 an 传递Array<ANode>
给需要 的函数Array<Node>
,即使Node
is ANode | BNode
:
type ANode = {type: 'a', value: string};
type BNode = {type: 'b', count: number};
type Node = ANode | BNode;
function getFirstNodeType(nodes: Array<Node>): string {
return nodes[0].type;
}
// works
const nodesSupertype: Array<Node> = [{type: 'a', value: 'foo'}];
getFirstNodeType(nodesSupertype);
// error
const nodesSubtype: Array<ANode> = [{type: 'a', value: 'foo'}];
getFirstNodeType(nodesSubtype); // error
16: getFirstNodeType(nodesSubtype); // error
^ Cannot call `getFirstNodeType` with `nodesSubtype` bound to `nodes` because property `value` is missing in `BNode` [1] but exists in `ANode` [2] in array element.
References:
6: function getFirstNodeType(nodes: Array<Node>): string {
^ [1]
15: const nodesSubtype: Array<ANode> = [{type: 'a', value: 'foo'}];
^ [2]
16: getFirstNodeType(nodesSubtype); // error
^ Cannot call `getFirstNodeType` with `nodesSubtype` bound to `nodes` because string literal `a` [1] is incompatible with string literal `b` [2] in property `type` of array element.
References:
1: type ANode = {type: 'a', value: string};
^ [1]
2: type BNode = {type: 'b', count: number};
^ [2]
解决方案
推荐阅读
- python-3.x - 在后台使用 selenium chrome 浏览器(不是无头模式)?
- javascript - 何时进行代码拆分(React-Suspense 和 Lazy)
- python - int() 是独立函数还是实际上是 int 类的 _init_ 构造函数方法?
- azure - 关于表单识别器、OCR 和 labeltool 容器的容器
- python - 如何在 django 的自定义用户模型中创建超级用户?
- visual-studio-code - 无法更改 vscode python 解释器以离开虚拟环境
- data-structures - 性能最好的通用数据结构是什么?
- routes - ASP.NET Core 3.1 MVC:路由不适用于区域
- sql - 为什么其中一个 SQL 查询有效,而另一个无效?
- java - Google Cloud App Engine - Eclipse 在 app.yaml 中显示“运行时:java 11”不是 Java