2017-08-14 6 views
2

類似のコンストラクタ(受入れエントリ)を持つ多くのサブクラスを持つクラスAbstractCollectionがあるとします。 AbstractCollectionclone()メソッドを実装することは可能ですか?実際のサブクラスの新しいインスタンスを作成して返し、エントリを渡しますか?TypeScriptでclone()メソッドを実装するにはどうすればよいですか?

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

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

答えて

2

もちろんの事、あなたが探していることは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]} 

code in playground

関連する問題