Provided is the interface that corresponds to the instance type of an anonymous class:
interface ISomeInterface {
prop: string;
method(): void;
}
In addition, it can be beneficial to define an interface corresponding to the constructor of the class. This interface would encompass any static properties of the constructor, along with the construct signature of the class, as demonstrated below:
interface SomeInterfaceConstructor {
new(prop: string): ISomeInterface;
}
The construct signature
new(prop: string): ISomeInterface
indicates that if you have a value
c
of type
SomeInterfaceConstructor
, you can invoke
new c("foobar");
to obtain an
ISomeInterface
instance. It's important to note that this syntax does not imply that
SomeInterfaceConstructor
has a method named
"new"
, despite the appearance.
By assigning a name to the constructor's interface, you can simply have createClass()
return that specified type:
function createClass(): SomeInterfaceConstructor {
return class implements ISomeInterface {
constructor(public prop: string) { }
method() {
console.log("My prop is " + this.prop);
}
}
}
Testing the functionality, you can observe that it functions as expected:
const c = createClass();
// const c: SomeInterfaceConstructor;
const i = new c("foobar");
// const i: ISomeInterface
i.method(); // My prop is foobar
export { createClass }
When exporting createClass()
, it might be worthwhile to also export the SomeInterfaceConstructor
type, as well as ISomeInterface
if it's not already exported or defined elsewhere.
Link to Playground for code