【问题标题】:Typescript: create instance in base class of a type defined in extending class / dynamic return type打字稿:在扩展类/动态返回类型中定义的类型的基类中创建实例
【发布时间】:2016-04-14 01:44:25
【问题描述】:

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

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

还有,第二个问题 - Base 类中的样式获取器能否返回正确的样式类型(如果是 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.

【问题讨论】:

    标签: typescript


    【解决方案1】:

    基本上,您所做的是从构造函数调用虚方法,这是一个禁忌,因为基类构造函数必须在派生类初始化发生之前完成。解决方案是将执行推迟到以后,以便派生类可以覆盖基类值:

    class Base {
        styleType:typeof Style = Style;
        private _style:Style;
    
        constructor(){ }
    
        // Lazy initialization
        public get style():Style{
            return this._style || (this.style = new this.styleType());
        }
    }
    

    【讨论】:

    • 谢谢 - 这确实解决了第一个问题(创建了正确的样式类型)。第二个怎么样 - 样式获取器返回类型是否可能是 BetterStyle(如果它是 BetterBase 实例)?
    • 目前无法实现自动化。不过,您可以将 Base 设为泛型并要求派生类提供具体类型。
    • 通过在每个扩展 Base 的类中添加 getter,对吧?
    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 2020-08-18
    • 2021-10-09
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2018-07-01
    相关资源
    最近更新 更多