首页 > 解决方案 > 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;
}

但这不是我想要的。如果我进入继承过程,那是因为我想要通用方法来删除每个孩子中的代码。

我找到了这篇文章,但我在理解并将其实施到我的场景中时遇到了一些困难

标签: typescriptoopinheritance

解决方案


您可以使用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;
    }
}

推荐阅读