gpt4 book ai didi

javascript - 如何允许任何泛型作为参数传递?

转载 作者:行者123 更新时间:2023-12-02 22:15:22 26 4
gpt4 key购买 nike

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

/* @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<ActualType>作为需要 StateOne<InterfaceType> 的参数.

最佳答案

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

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

关于javascript - 如何允许任何泛型作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59399992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com