首页 > 解决方案 > 如何通过另一个类扩展类?

问题描述

我有树类:

class ClassificatorOrganizationsModel {
    protectedcode: string | undefined;
}

class EduUnitModel {
  paren1tId: number | undefined;
  paren2tId: number | undefined;
  paren3tId: number | undefined;
  phone: string | undefined;
}

export class EduOrganizationModel {
  regionId: number | undefined;
  addressId: number | undefined;

}

我需要该类EduOrganizationModel将由EduUnitModeland扩展ClassificatorOrganizationsModel

结果,我需要获得EduOrganizationModel包括孩子在内的所有属性的课程。

所以,我不能这样做:

class EduOrganizationModel extends EduUnitModel, ClassificatorOrganizationsModel {
}

如何解决?

标签: typescripttypescript2.0

解决方案


您可以使用 Mixins https://www.typescriptlang.org/docs/handbook/mixins.html 进行多重继承。

interface EduOrganizationModel extends EduUnitModel, ClassificatorOrganizationsModel {}
applyMixins(EduOrganizationModel, [EduUnitModel, ClassificatorOrganizationsModel]);

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
        });
    });
}

推荐阅读