typescriptmethod-signaturenewable

How to specify any newable type in TypeScript?


I tried with this but it doesn't work. Foo is just a test of what works. Bar is the real try, it should receive any newable type but subclasses of Object isn't valid for that purpose.

class A {

}
class B {
    public Foo(newable: typeof A):void {

    }
    public Bar(newable: typeof Object):void {

    }
}

var b = new B();
b.Foo(A);
b.Bar(A); // <- error here

Solution

  • You can use { new(...args: any[]): any; } to allow any object with a constructor with any arguments.

    class A {
    
    }
    
    class B {
        public Foo(newable: typeof A):void {
    
        }
    
        public Bar(newable: { new(...args: any[]): any; }):void {
    
        }
    }
    
    var b = new B();
    b.Foo(A);
    b.Bar(A);  // no error
    b.Bar({}); // error