问题
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
回答1:
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
回答2:
If you want to enforce only certain newables, you can specify the constructor's return type
interface Newable {
errorConstructor: new(...args: any) => Error; // <- put here whatever Base Class you want
}
equivalent
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;
}
testing
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
};
来源:https://stackoverflow.com/questions/33224047/how-to-specify-any-newable-type-in-typescript