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"); }
}
}
我正在尝试实现这样的代码,我认为这些代码结构良好。
这有可能在反应中,让一个类作为另一个的子类 - 并将它作为一个抽象属性(最好是静态的)。
我想我得到了这个。
在这样的TS语法中,attribute: Item { ...
意味着attribute
是类Item
的实例。如果你想让attribute
成为类Item(不是实例),你应该使用像这样的语法attribute: { new (...args): Item } {...
。所以最终代码应如下所示:
abstract class ModelView<M extends Model> {}
abstract class Model {
public View: { new(...args): ModelView<Model> };
getView(): ModelView<Model> {
return new this.View();
}
}
然后在Shape
课你可以这样做:
class Shape extends Model {
View = class {
constructor(){ console.log("view created"); }
}
}
代码将是类型安全的。
------ ------编辑
如果你想查看静态和只读,你必须改变一点点getView
实现:
public static readonly View: { new(...args): ModelView<Model> };
getView(): ModelView<Model> {
return new Model.View();
}
您只是在寻找以下内容吗?
abstract class Model {
// don't use "class" here; the type of a constructor has new(...) in it:
abstract View: new () => ModelView<this>;
getView() {
return new this.View(); // View is an instance property, need "this"
}
}
abstract class ModelView<M extends Model> { }
class Shape extends Model {
View = class {
constructor(){ console.log("view created"); }
}
}
如果这符合您的需求,那就太好了。如果没有,请编辑您的问题以包含有关您的用例的更多信息。希望对你有所帮助。祝好运!