首页 文章

Typescript:在扩展类/动态返回类型中定义的类型的基类中创建实例

提问于
浏览
0

我有Base类,它定义了style和styleType属性 . 有一个Better类扩展了Base类,它用另一个值覆盖styleType .

是否可以在Base类中创建样式的实例,该样式是在Better类中定义的styleType?

而且,第二个问题 - 在Base类中可以获取样式的样式返回正确的类型(BetterStyle,如果它是BetterBase实例)吗?

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 .

1 回答

  • 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());
        }
    }
    

相关问题