`(子类型数组到超类型数组),javascript,arrays,flowtype"/>

首页 > 解决方案 > 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]

试用 Flow 演示

同样,我不能将 an 传递Array<ANode>给需要 的函数Array<Node>,即使Nodeis 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 演示

标签: javascriptarraysflowtype

解决方案



推荐阅读