【发布时间】:2018-08-30 07:11:30
【问题描述】:
我有一个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]
同样,我不能将Array<ANode> 传递给采用Array<Node> 的函数,即使Node 是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]
【问题讨论】:
-
这个问题和Flow Array type fails on subset of that type的问题差不多。我发布了这个问题,而不是在该问题上添加新答案,原因有两个:为人们提供更好、简化的示例以了解问题,并为搜索此问题的人们提及不同的关键字。这两个原因中的第一个可能表明这个问题不应该作为重复关闭。
标签: javascript arrays flowtype