Creating a simple Cloneable interface for all my data classes in JavaScript is a straightforward task. However, when it comes to typing it properly in TypeScript, things get a bit more complex.
Currently, I am putting together a solution like this:
class BaseClass implements Cloneable {
clone() {
return new (this.constructor as any)(this.data);
}
}
My goal is for the clone
methods of all the sub-classes to return their own type instead of just BaseClass
. For example:
class ExampleSubclass extends BaseClass {}
const foo = new ExampleSubclass();
const bar = foo.clone(); // Hoping that `bar` will be of type `ExampleSubclass`, not `BaseClass` or `Cloneable`.
I'm wondering if there is a better way to implement late bindings for this scenario?