typescript - Typescript - 具有返回类型的方法继承
问题描述
我想创建一个包含所有孩子都会使用的方法的基类。但是,我无法继承返回类对象的方法。
这是我想要实现的目标:
export class BaseModel {
constructor(){}
fromJson(model: BaseModel): BaseModel {
if (!model) {
return new BaseModel();
}
Object.keys(model)
.map(key => this[key] = model[key]);
return this;
}
}
export class ChildModel extends BaseModel {
}
...
const child: ChildModel = new ChildModel().fromJson(someJson);
...
但我得到编译错误:
“BaseModel”类型不能分配给“ChildModel”类型。
我能够实现这一点的唯一方法是在 MyChild 类中定义“fromJson”方法,如下所示:
fromJson(child: ChildModel): ChildModel {
super.fromJson(child);
return this;
}
但这不是我想要的。如果我进入继承过程,那是因为我想要通用方法来删除每个孩子中的代码。
我找到了这篇文章,但我在理解并将其实施到我的场景中时遇到了一些困难
解决方案
您可以使用this
始终引用实例本身类型的类型。但是,它要求您转换new BaseModel()
为this
:
export class BaseModel {
constructor(){}
fromJson(model: BaseModel): this {
if (!model) {
return new BaseModel() as this;
}
Object.keys(model)
.map(key => this[key] = model[key]);
return this;
}
}
推荐阅读
- android - 电子邮件附件仅适用于更改的 extra_text
- angularjs - 过滤器插值问题
- python-3.x - 在 Python 中保留路径的一部分
- angular - 三元运算符中的多个条件检查
- sonarlint-vs - Visual Studio 上的 SonarLint 未在错误窗格中显示警告
- c++ - 在循环迭代期间保存对向量中的 void 指针的引用
- plot - 如何加快 NIntegrate 计算?
- python - TensorFlow:ValueError:不支持无值
- python - 如何通过以太网将树莓派连接到 plc?
- javascript - 即使 JS 函数返回 false,表单也会被提交