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

后端 未结 7 825
渐次进展
渐次进展 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:24

    is it possible to hand a class to a method? And if so, does the type "any" include such class-types?

    Yes and yes. any includes every type.

    Here's an example of a type that includes only classes:

    type Class = { new(...args: any[]): any; };
    

    Then using it:

    function myFunction(myClassParam: Class) {
    }
    
    class MyClass {}
    
    myFunction(MyClass); // ok
    myFunction({}); // error
    

    You shouldn't have an error passing in a class for Function though because that should work fine:

    var func: Function = MyClass; // ok
    

提交回复
热议问题