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

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

    Type<T> from @angular/core is a proper interface for Class.

    export interface Type<T> extends Function {
        new (...args: any[]): T;
    }
    

    You can use it to keep reference to class, instead of instance of this class:

    private classRef: Type<MyCustomClass>;
    

    or

    private classRef: Type<any>;
    

    According to background of your question with @ViewChild:

    @ViewChild allows to inject "string selector" / Component / Directive

    Signature of Type<any> | Function | string is an abstract signature that allows us to inject all of above.

    0 讨论(0)
  • 2020-12-07 19:08

    Following worked for me:

    type ClassRef = new (...args: any[]) => any;
    

    my use case:

     interface InteractionType { [key: string]: ClassRef; }
    
    0 讨论(0)
  • 2020-12-07 19:15

    The simplest solution would be let variable: typeof Class.

    Here an example:

    class A {
      public static attribute = "ABC";
    }
    
    function f(Param: typeof A) {
      Param.attribute;
      new Param();
    }
    
    
    f(A);
    
    0 讨论(0)
  • 2020-12-07 19:24

    Angular internally declare Type as:

    export interface Type<T> extends Function { new (...args: any[]): T; }
    

    With TypeScript3 it should be possible to add types for arguments without function overloading:

    export interface TypeWithArgs<T, A extends any[]> extends Function { new(...args: A): T; } 
    

    Example:

    class A {}
    
    function create(ctor: Type<A>): A {
        return new ctor();
    }
    
    let a = create(A);
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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

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