参数

时间:2016-07-11 16:18:17

标签: typescript typescript1.8

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

class MyClass { ... }

let myVar: typeof MyClass = MyClass;

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

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 */

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

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

知道怎么解决吗?

2 个答案:

答案 0 :(得分: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

code in playground

修改

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

{ new(): Class }

例如在打字稿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签名和一堆静态功能 在您的情况下,您还可以将其定义为:

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();
    }
}

答案 1 :(得分:-1)

您可以通过以下类型进行声明。

variableName:className的类型;

typeof是Javascript关键字。

相关问题