Abstract constructor type in TypeScript

前端 未结 4 1366
眼角桃花
眼角桃花 2020-12-14 15:03

The type signature for a non-abstract class (non-abstract constructor function) in TypeScript is the following:

declare type ConstructorFunction = new (...ar         


        
相关标签:
4条回答
  • 2020-12-14 15:41

    Having the same problem. I guess, an essence of abstract class constructor signature is an absense of new ( ... ) : X thingy in its declaration. That's why it can be declared explicitly.

    However. You can do this, and it will compile.

    var UtilityClass: typeof Utilities  = Utilities;
    

    typeof Something is a nice way to reference constructor types, however, it cannot be extended.

    And in any case you can do thing like this:

    var UtilityClass: ConstructorFunction = <any> Utilities;
    
    0 讨论(0)
  • 2020-12-14 15:54

    Was just struggling with a similar problem myself, and this seems to work for me:

    type Constructor<T> = Function & { prototype: T }
    
    0 讨论(0)
  • 2020-12-14 15:55

    The whole point with abstract classes (in OO in general) is that you can not instantiate them, you need a concrete non-abstract implementation.

    I assume that you want to have different implementations to that abstract class and want to be able to receive one of those implementations (as a parameter or something of the likes).
    If that's the case, then maybe this might solve your problem:

    declare type ConstructorFunction<T extends Utilities> = new (...args: any[]) => T;
    
    abstract class Utilities { }
    
    class MyUtilities extends Utilities { }
    
    var UtilityClass: ConstructorFunction<MyUtilities> = MyUtilities; 
    
    0 讨论(0)
  • This solution:

    type Constructor<T> = Function & { prototype: T }
    

    won't allow you to create instances of this type using new keyword.

    There's another simple solution:

    type Constructor = new (...args: any[]) => AbstractClass
    
    0 讨论(0)
提交回复
热议问题