如何在 TypeScript 中实现 clone() 方法?



假设有一个类AbstractCollection可能有许多子类,这些子类具有类似的构造函数(接受条目(。是否可以在AbstractCollection中实现一个clone()方法,该方法将创建并返回实际子类的新实例,传入条目?

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

当然,您要查找的是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);
}
}

然后:

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]}

(操场上的代码(

最新更新