我试过这个,但它没有用。 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
答案 0 :(得分:9)
您可以使用{ 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
答案 1 :(得分:0)
如果您只想强制某些新事物,则可以指定构造函数的返回类型
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
};