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);
ありがとう:ソリューションは、派生クラスが基底クラスの値を上書きすることができるように後になるまでその実行を延期することです。 2位はどうでしょうか?スタイルゲッターの戻り値の型がBetterStyle(BetterBaseのインスタンスの場合)になる可能性はありますか? – zeroin
これは現在自動化できません。あなたは 'Base'を汎用的にすることができ、具体的な型を提供するために派生物を必要とします。 –
Baseを拡張する各クラスにgetterを追加することで、右か? – zeroin