Is there a type for “Class” in Typescript? And does “any” include it?

后端 未结 7 801
渐次进展
渐次进展 2020-12-07 18:34

In Java, you can give a class to a method as a parameter using the type \"Class\". I didn\'t find anything similar in the typescript docs - is it possible to hand a class to

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-07 19:26

    The equivalent for what you're asking in typescript is the type { new(): Class }, for example:

    class A {}
    
    function create(ctor: { new(): A }): A {
        return new ctor();
    }
    
    let a = create(A); // a is instanceof A
    

    (code in playground)

    The code above will allow only classes whose constructor has no argument. If you want any class, use new (...args: any[]) => Class

提交回复
热议问题