weekens
weekens

Reputation: 8292

How could one implement clone() method in TypeScript?

Suppose there is a class AbstractCollection that may have many sub-classes, which have similar constructors (accepting entries). Is it possible to implement a clone() method in AbstractCollection, that would create and return a new instance of actual sub-class, passing in the entries?

class AbstractCollection<T> {
  constructor(items: T[]) {
    // ...
  }

  clone(): AbstractCollection<T> {
    // TODO: implement
  }
}

Upvotes: 2

Views: 66

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

Sure thing, what you're looking for is this.constructor:

class AbstractCollection<T> {
    private items: T[];

    constructor(items: T[]) {
        this.items = items;
    }

    clone(): AbstractCollection<T> {
        return new (this.constructor as { new(items: T[]): AbstractCollection<T>})(this.items);
    }
}

And then:

class MyCollection1 extends AbstractCollection<string> {}

class MyCollection2 extends AbstractCollection<number> { }

let a = new MyCollection1(["one", "two", "three"]);
let clonedA = a.clone();
console.log(clonedA); // MyCollection1 {items: ["one", "two", "three"]}

let b = new MyCollection2([1, 2, 3]);
let clonedB = b.clone();
console.log(clonedB); // MyCollection2 {items: [1, 2, 3]}

(code in playground)

Upvotes: 2

Related Questions