我试过这个,但它不起作用。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
我试过这个,但它不起作用。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
如果您只想强制执行某些新变量,您可以指定构造函数的返回类型
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
};