流数组的多态性和子类型

问题描述 投票:0回答:1

我无法像使用Java之类的其他语言那样,使多态子类型在具有Flow泛型的数组中工作。

请考虑以下内容。

interface Person {
    name:string;
}

class Employee implements Person {
    name:string;
    badge:string;
}

interface Workplace {
    people:Array<Person>;
}

class MyOffice implements Workplace {
    people:Array<Employee>;  // ERROR: Incompatible with Workplace.people
}

这在Java中也会失败;但是Java可以通过指示people中的Workplace数组包含Person的子类型来正确实现此目的。

interface Workplace {
    people:Array<? extends Person>; // PSUEDO CODE: This is how Java supports subtypes
}

我无法在Flow中找到类似的机制。流程在此处讨论方差:https://flow.org/en/docs/lang/variance/#toc-covariancehttps://flow.org/en/docs/lang/depth-subtyping/

这建议以下应该起作用。

interface Workplace {
    people:Array<+Person>;
}

但是此语法失败。

Flow中有没有一种方法可以声明数组协变类型?

我无法像使用Java之类的其他语言那样,使多态子类型在具有Flow泛型的数组中工作。考虑以下。接口Person {name:string; }类Employee ...

javascript flowtype
1个回答
0
投票

流量差异需要一些习惯。正如您所提到的,核心问题是,如果

© www.soinside.com 2019 - 2024. All rights reserved.