参数中的泛型和typeof [英] Generic and typeof T in the parameters

查看:94
本文介绍了参数中的泛型和typeof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在TypeScript中,我可以将变量的类型定义为类的类型.例如:

In TypeScript I can define the type of a variable as the type of a class. For example:

class MyClass { ... }

let myVar: typeof MyClass = MyClass;

现在,我想将其与通用类一起使用,如下所示:

Now I want to use this with a generic class, something like this:

class MyManager<T> {
    constructor(cls: typeof T) { ... }
    /* some other methods, which uses instances of T */
}

let test = new MyManager(MyClass); /* <MyClass> should be implied by the parameter */

因此,我想给我的经理类另一个类(其构造函数),因为经理需要检索与 class 相关的静态信息.

So, I want to give my manager class another class (its constructor), because the manager needs to retreive static information associated with the class.

在编译我的代码时,它说找不到我的构造函数所在的名称'T'.

When compiling my code, it says that it cannot find name 'T', where my constructor is.

有什么办法解决吗?

推荐答案

您可以使用以下类型的构造函数:{ new (): ClassType }.

You can use this type of constructors: { new (): ClassType }.

class MyManager<T> {
    private cls: { new(): T };

    constructor(cls: { new(): T }) {
        this.cls = cls;
    }

    createInstance(): T {
        return new this.cls();
    }
}

class MyClass {}

let test = new MyManager(MyClass);
let a = test.createInstance();
console.log(a instanceof MyClass); // true

(在打字稿中描述类类型的正确方法是使用以下内容:

The proper way to describe a class type in typescript is using the following:

{ new(): Class }

例如在打字稿 lib.d.ts中ArrayConstructor :

For example in the typescript lib.d.ts ArrayConstructor:

interface ArrayConstructor {
    new (arrayLength?: number): any[];
    new <T>(arrayLength: number): T[];
    new <T>(...items: T[]): T[];
    (arrayLength?: number): any[];
    <T>(arrayLength: number): T[];
    <T>(...items: T[]): T[];
    isArray(arg: any): arg is Array<any>;
    readonly prototype: Array<any>;
}

这里有3个不同的ctor签名以及一堆静态函数.
在您的情况下,您也可以像这样定义它:

Here you have 3 different ctor signatures plus a bunch of static functions.
In your case you can also define it like:

interface ClassConstructor<T> {
    new(): T;
}

class MyManager<T> {
    private cls: ClassConstructor<T>;

    constructor(cls: ClassConstructor<T>) {
        this.cls = cls;
    }

    createInstance(): T {
        return new this.cls();
    }
}

这篇关于参数中的泛型和typeof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆