Javascript 如何允许任何泛型作为参数传递?
如何声明允许传递任何泛型类型的类型?下面是一个我正在尝试做的简化示例:Javascript 如何允许任何泛型作为参数传递?,javascript,class,flowtype,Javascript,Class,Flowtype,如何声明允许传递任何泛型类型的类型?下面是一个我正在尝试做的简化示例: /* @flow */ type InterfaceType = { var1 : number, }; type ActualType = InterfaceType & { var2 : string, }; class StateOne<T : InterfaceType> { constructor(arg : T) : StateOne<T> {
/* @flow */
type InterfaceType = {
var1 : number,
};
type ActualType = InterfaceType & {
var2 : string,
};
class StateOne<T : InterfaceType> {
constructor(arg : T) : StateOne<T> {
return this;
}
}
class StateTwo {
constructor(stateOne : StateOne<InterfaceType>) : StateTwo {
return this;
}
}
let variable : ActualType = {
var1: 1,
var2: "text",
}
let stateOne : StateOne<ActualType> = new StateOne(variable);
let stateTwo : StateTwo = new StateTwo(stateOne);
/*@flow*/
类型接口类型={
var1:数字,
};
类型ActualType=InterfaceType&{
var2:string,
};
州一级{
构造函数(arg:T):StateOne{
归还这个;
}
}
第二类{
构造函数(stateOne:stateOne):state2{
归还这个;
}
}
let变量:实际类型={
var1:1,
var2:“文本”,
}
设stateOne:stateOne=newstateone(变量);
设stateTwo:stateTwo=新stateTwo(statetone);
下面是我得到的流错误:
29: let stateTwo : StateTwo = new StateTwo(stateOne);
^ Cannot call `StateTwo` with `stateOne` bound to `stateOne` because property `var2` is missing in `InterfaceType` [1] but exists in object type [2] in type argument `T` [3].
References:
18: constructor(stateOne : StateOne<InterfaceType>) : StateTwo {
^ [1]
7: type ActualType = InterfaceType & {
^ [2]
11: class StateOne<T : InterfaceType> {
^ [3]
29:let stateTwo:stateTwo=新stateTwo(statetone);
^无法调用绑定到“stateOne”的“StateToo”,因为“InterfaceType”[1]中缺少属性“var2”,但该属性存在于类型参数“T”[3]中的对象类型[2]中。
参考资料:
18:构造函数(stateOne:stateOne):state2{
^ [1]
7:类型ActualType=接口类型和{
^ [2]
11:StateOne班{
^ [3]
我的想法是,由于
ActualType
是一个更具体的InterfaceType
,因此我可以将StateOne
作为需要StateOne的参数传递,我可以通过向构造函数添加泛型来解决错误:
class StateTwo {
constructor<T : InterfaceType>(stateOne : StateOne<T>) : StateTwo {
return this;
}
}
class state2{
构造函数(stateOne:stateOne):state2{
归还这个;
}
}