【问题标题】:How to allow any generic to be passed as argument?如何允许任何泛型作为参数传递?
【发布时间】:2020-04-11 11:26:07
【问题描述】:

如何声明一个允许传递任何泛型类型的类型?这是我正在尝试做的一个简化示例:

/* @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);

这是我得到的流程错误:

    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]

我的想法是,由于ActualType 是更具体的InterfaceType,那么我可以将StateOne&lt;ActualType&gt; 作为需要StateOne&lt;InterfaceType&gt; 的参数传递。

【问题讨论】:

    标签: javascript class flowtype


    【解决方案1】:

    我能够通过向构造函数添加泛型来解决错误:

    class StateTwo {
        constructor<T : InterfaceType>(stateOne : StateOne<T>) : StateTwo {
            return this;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-28
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多