参数中的通用和类型T.

Sim*_*mon 9 typescript typescript1.8

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

class MyClass { ... }

let myVar: typeof MyClass = MyClass;
Run Code Online (Sandbox Code Playgroud)

现在我想将它与泛型类一起使用,如下所示:

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 */
Run Code Online (Sandbox Code Playgroud)

所以,我想给我的经理类另一个类(它的构造函数),因为管理器需要检索与该类关联的静态信息.

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

知道怎么解决吗?

Nit*_*mer 15

您可以使用这种类型的构造函数:{ 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
Run Code Online (Sandbox Code Playgroud)

(游乐场代码)


编辑

在typescript中描述类类型的正确方法是使用以下方法:

{ new(): Class }
Run Code Online (Sandbox Code Playgroud)

例如在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>;
}
Run Code Online (Sandbox Code Playgroud)

这里有3个不同的ctor签名和一堆静态函数.
在您的情况下,您还可以将其定义为:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它不是那么明显的`{new():T}`,特别是因为构造函数被定义为`constructor()`而人们宁愿期待像`T`,`typeof T`等等. (2认同)