我有一个类型为
例如,我不能将类型为
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]
同样地,即使 Node
是 ANode | BNode
,我也不能将 Array<ANode>
传递给接受 Array<Node>
的函数:
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]