Search code examples
typescriptclassinheritanceclonelate-binding

How do I create a late-binding clone method in TypeScript classes?


I want to make a simple Cloneable interface for all my data classes, it's easy to do it in JavaScript. But it's not obvious on how to properly type it in TypeScript.

I am currently hacking it together like this:

class BaseClass implements Cloneable {
  clone() {
    return new (this.constructor as any)(this.data);
  }
}

I want the clone methods of all the sub-classes returns their own type instead of BaseClass. For example:

class ExampleSubclass extends BaseClass {}

const foo = new ExampleSubclass();
const bar = foo.clone(); // Expecting `bar` to be `ExampleSubclass`, neither `BaseClass` nor `Cloneable`.

Is there a more proper way to do late bindings?


Solution

  • I believe you should cast it

    class BaseClass {
      clone() {
        return new (this.constructor as any)(this.data) as typeof this;
      }
    }