Given the following interface corresponding to the anonymous class's instance type,
// 定义一个接口用于类实现
interface ISomeInterface {
prop: string;
method(): void;
}
it is also helpful for you to define an interface corresponding to the class's constructor. This would include any static properties of the constructor, as well as the class's construct signature, like this:
// 构造函数接口
interface SomeInterfaceConstructor {
new(prop: string): ISomeInterface;
}
That new(prop: string): ISomeInterface means if you have a value c of type SomeInterfaceConstructor, then you can call new c("foobar"); and get an ISomeInterface out. (Note that it does not mean that SomeInterfaceConstructor has a method named "new", even though the syntax looks like that).
Armed with a name for the constructor's interface, you can simply have createClass() return that type:
function createClass(): SomeInterfaceConstructor {
return class implements ISomeInterface {
constructor(public prop: string) { }
method() {
console.log("My prop is " + this.prop);
}
}
}
And you can see that it works:
const c = createClass();
// const c: SomeInterfaceConstructor;
const i = new c("foobar");
// const i: ISomeInterface
i.method(); // My prop is foobar
export { createClass }
And when you export createClass(), you might want to export the SomeInterfaceConstructor type, as well as ISomeInterface if it's not already exported (or defined elsewhere).