I am exploring the creation of an interface that enforces implementing classes to have a method that returns an instance of themselves, preferably statically.
Consider the following interface:
interface MyInterface {
foo: string;
getNewInstance(): MyInterface;
}
An example implementation would look like this:
class MyImplementation implements MyInterface {
foo: string;
bar: string;
getNewInstance(): MyInterface {
return {foo: "test"};
}
}
However, I am struggling to find a way to mandate that the implementation must return an instance of itself. Additionally, making it static proves to be even more challenging.
In my specific scenario, I am using MyInterface as a generic in
AbstractClass<T extends MyInterface>
, and I aim for MyClass<MyImplementation>
to generate a new instance of MyImplementation
.
Although I understand there are alternative methods to achieve this, such as requiring the class using the generic to implement it, like so:
AbstractClass<T extends MyInterface> {
abstract getNewInstance(): T;
}
I still wanted to explore if my initial idea was feasible, as it could streamline the declaration and instance generation. Any insights or suggestions would be greatly appreciated. Thank you.