2016-04-13 22 views
0

スタイルとスタイルのプロパティが定義されたBaseクラスがあります。 Baseクラスを拡張するBetterクラスがあり、styleTypeを別の値でオーバーライドします。Typescript:拡張クラス/動的戻り型で定義された型の基本クラスのインスタンスを作成します。

Betterクラスで定義されたstyleTypeであるstyleのインスタンスをBaseクラスで作成することはできますか?

そして、2番目の質問 - 基本クラスのスタイルのゲッターは、スタイルの正しいタイプ(BetterBaseインスタンスの場合はBetterStyle)を返します。

class Base { 
    styleType:typeof Style = Style; 
    private _style:Style; 

    constructor(){ 
     this._style = new this.styleType(); 
    } 
    // how to define return type so that it would beof styleType? 
    public get style():Style{ 
     return this._style; 
    } 
} 

class Style{ 
    public color; 
} 

class BetterBase extends Base{ 
    styleType:typeof BetterStyle = BetterStyle; 
} 

class BetterStyle extends Style{ 
    public betterColor; 
} 

var betterBase = new BetterBase(); 
betterBase.style.color = "#FF0000"; 
console.log(betterBase.style); // incorrect, outputs Style, not BetterStyle 
console.log(betterBase.styleType); 

Playground here

答えて

2

基本的には、コンストラクタから仮想メソッドを呼び出すことです。これは、派生クラスの初期化が行われる前に基本クラスのコンストラクタが終了する必要があるためです。これは確かに最初の問題を(スタイルの正しい型が作成される)解決 -

class Base { 
    styleType:typeof Style = Style; 
    private _style:Style; 

    constructor(){ } 

    // Lazy initialization 
    public get style():Style{ 
     return this._style || (this.style = new this.styleType()); 
    } 
} 
+0

ありがとう:ソリューションは、派生クラスが基底クラスの値を上書きすることができるように後になるまでその実行を延期することです。 2位はどうでしょうか?スタイルゲッターの戻り値の型がBetterStyle(BetterBaseのインスタンスの場合)になる可能性はありますか? – zeroin

+0

これは現在自動化できません。あなたは 'Base'を汎用的にすることができ、具体的な型を提供するために派生物を必要とします。 –

+0

Baseを拡張する各クラスにgetterを追加することで、右か? – zeroin

関連する問題