简体   繁体   中英

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?

I believe you should cast it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM