【问题标题】:Typescript type parameter with gernic argument list带有通用参数列表的打字稿类型参数
【发布时间】:2019-05-06 22:49:37
【问题描述】:

是否可以像在 C++ 中一样将类型参数用作泛型?

interface Genic1ParamWrapperConstructor<T>{
    new<T2>():T<T2>;
}

有趣的部分是 T,因为 typescript 编译器会生成错误提示:Type 'T' is not a generic

【问题讨论】:

标签: typescript typescript-generics


【解决方案1】:

要将其与界面一起使用,例如您的情况,您需要类似于

interface GenericIdentityFn<T> {
    (arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn<number> = identity;

请注意,您应该在接口上使用来设置整个接口的类型,或者单独为每个方法设置类型。这可能就是错误所在。 所以:

interface Genic1ParamWrapperConstructor<T>{
    new(arg: T): T;
}

或者

interface Genic1ParamWrapperConstructor{
    new<T>(arg: T): T;
}

取决于您的偏好。

你也可以使用任何参数

    function identity(arg: any): any {
        return arg;
    }
let output = identity("myString");  // type of output will be 'string'

更多信息可以找到here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2016-09-20
    • 1970-01-01
    • 2017-01-18
    相关资源
    最近更新 更多