javascript - 打字稿中的抽象内部类
问题描述
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"); }
}
}
我正在尝试实现这样的代码,我认为它结构良好。
这是否可能在反应中,将一个类作为另一个类的子类 - 并将其作为一个抽象属性(最好是静态的)。
解决方案
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.
------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();
}
推荐阅读
- c# - double.TryParse() 不应该返回零 (0)
- c++ - 在 C++ 中对数组进行洗牌和平方的函数的问题
- xml - python中的Apache Beam数据流作业未运行
- python - 如何使用 python ast 模块分析 if 语句
- mongodb - Mongo查询每天使用时间参数获取1个文档
- python - 如何检查列表和系列之间的相似元素(可能不相同且长度不同)
- azure-machine-learning-service - 在 aml 服务中装载从 Azure 数据湖创建的数据集
- python - 如何使用 python pandas 将标题写入多个工作表
- python - 在 Django Q 对象中查找最新日期
- wso2 - 从后端接收数据时出现 JSON 有效负载错误