如何在 TypeScript 中指定任何新类型?

How to specify any newable type in TypeScript?

我试过了,但没用。 Foo 只是对什么有效的测试。 Bar 是真正的尝试,它应该接收任何可更新的类型,但 Object 的子类对此无效。

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

您可以使用 { new(...args: any[]): any; } 来允许任何具有带有任何参数的构造函数的对象。

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

如果您只想强制执行某些新功能,您可以指定构造函数的 return 类型

interface Newable {
  errorConstructor: new(...args: any) => Error; // <- put here whatever Base Class you want
}

等价

declare class AnyError extends Error { // <- put here whatever Base Class you want
  // constructor(...args: any) // you can reuse or override Base Class' contructor signature
}

interface Newable {
  errorConstructor: typeof AnyError;
}

测试

class NotError {}
class MyError extends Error {}

const errorCreator1: Newable = {
  errorConstructor: NotError, // Type 'typeof NotError' is missing the following properties from type 'typeof AnyError': captureStackTrace, stackTraceLimitts
};

const errorCreator2: Newable = {
  errorConstructor: MyError, // OK
};