首页 > 解决方案 > 打字稿中的抽象内部类

问题描述

abstract class Model {
    abstract class View extends ModelView<this>;

    getView(){
        return new View();
    }
}

abtract class ModelView<M extends Model> {}

class Shape extends Model {
    View = class {
        constructor(){ console.log("view created"); }
    }
}

我正在尝试实现这样的代码,我认为它结构良好。

这是否可能在反应中,将一个类作为另一个类的子类 - 并将其作为一个抽象属性(最好是静态的)。

标签: javascripttypescriptecmascript-6polymorphism

解决方案


I think i got this.

In TS syntax like this attribute: Item { ... means that attribute is instance of class Item. If you want attribute to be class Item (not a instance) you should use syntax like this attribute: { new (...args): Item } {.... So final code should looks like:

abstract class ModelView<M extends Model> {}


abstract class Model {
    public View: { new(...args): ModelView<Model> };

    getView(): ModelView<Model> {
        return new this.View();
    }
}

and then in Shape class you can do this:

class Shape extends Model {
    View = class {
        constructor(){ console.log("view created"); }
    }
}

And code will be type safe.

Playground

------Edited------

If you want to View be static and readonly you have to change little bit getView implementation to this:

public static readonly View: { new(...args): ModelView<Model> };

getView(): ModelView<Model> {
    return new Model.View();
}


推荐阅读