0

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

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

有趣的部分是T<T2>因为打字稿编译器生成一个错误说: Type 'T' is not a generic

4

1 回答 1

0

要将其与接口一起使用,例如在您的情况下,您需要类似于以下内容的东西

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'

更多信息可以在这里找到

于 2018-12-05T11:37:30.133 回答