Generic and typeof T in the parameters

前端 未结 2 1398
孤街浪徒
孤街浪徒 2020-12-04 01:44

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;

相关标签:
2条回答
  • 2020-12-04 02:20

    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
    

    (code in playground)


    Edit

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

    { new(): Class }
    

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

    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 02:27

    You can just declare it by the following type.

    variableName: typeof ClassName;

    typeof is Javascript keyword.

    0 讨论(0)
提交回复
热议问题