Reputation: 8292
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
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]}
Upvotes: 2