类似于:
declare class $ReadOnlyArray<+T>
declare type React$Element<+ElementType: React$ElementType>
interface $Iterator<+Yield,+Return,-Next>
不是出现在properties前面的那种,这里回答Flow type, What does the `+` symbol mean in front a property?
最佳答案
这是我的理解,可能不完整。
通用类型中的协变,例如 type Container<+T> = {}
, 表示:如果 A
是 B
的子类型, 然后 Container<A>
是 Container<B>
的子类型.例如,这是允许的:
type Container<+T> = {};
class Parent {};
class Child extends Parent {};
function x(a: Container<Parent>) {}
const container: Container<Child> = {};
x(container);
因为Child
是 Parent
的子类型.但是如果你删除 +
,不再允许,Flow 在 x(container)
上给出错误,因为 container
不是 Container<Parent>
类型的有效值.
当然逆变是相反的:type Container<-T> = {}
意味着如果 A
是 B
的子类型, 然后 Container<B>
是 Container<A>
的子类型.所以这是合法的:
type Container<-T> = {};
class Parent {};
class Child extends Parent {};
function x(a: Container<Child>) {}
const container: Container<Parent> = {};
x(container);
请注意我对 Container<+T>
的定义或 Container<-T>
没有使用 T
类型根本。如果是这样,那么它的使用位置就会受到限制,类似于你可以在接口(interface)中使用逆变或协变属性(即它们变成只读或只写)的限制。我还没有弄清楚这些规则的细节。
关于javascript - 流类型, `+`和 `-`在泛型声明中做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51277329/