【发布时间】:2019-11-09 09:15:11
【问题描述】:
我无法让多态子类型在具有 Flow 泛型的数组中工作,就像在 Java 等另一种语言中那样。
考虑以下内容。
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 有一种方法可以正确实现这一点,方法是指示 Workplace 中的 people 数组将包含 Person 的子类型。
interface Workplace {
people:Array<? extends Person>; // PSUEDO CODE: This is how Java supports subtypes
}
我无法在 Flow 中找到类似的机制。 Flow 在这里讨论方差:https://flow.org/en/docs/lang/variance/#toc-covariance 和 https://flow.org/en/docs/lang/depth-subtyping/
这表明以下应该有效。
interface Workplace {
people:Array<+Person>;
}
但是这种语法失败了。
Flow 中有没有办法声明一个 Array 协变类型?
【问题讨论】:
标签: javascript flowtype