Typescript 如何通过另一个类扩展类?
我有树类:Typescript 如何通过另一个类扩展类?,typescript,typescript2.0,Typescript,Typescript2.0,我有树类: class ClassificatorOrganizationsModel { protectedcode: string | undefined; } class EduUnitModel { paren1tId: number | undefined; paren2tId: number | undefined; paren3tId: number | undefined; phone: string | undefined; } export cla
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通过EduUnitModel和ClassificatorOrganizationsModel进行扩展
因此,我需要获得包含所有属性(包括子级)的类EduOrganizationModel
因此,我不能这样做:
class EduOrganizationModel extends EduUnitModel, ClassificatorOrganizationsModel {
}
如何解决它?您可以使用mixin
用于多重继承
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));
});
});
}
TS不允许多重继承。不是没有一些黑客,但所有的变通方法都证实了这一事实。如果你绝对需要多重继承,我猜你是做错了什么——很多语言都不允许这样做,因为这是一堆蠕虫,是设计问题的磁石。我建议重新设计,将多重继承分解为更好的支持。问题是新类a{}可以包含与EduUnit模型相同的字段和一些自己的字段。这就是为什么我尝试使用多重继承来避免干燥。所以,它只是一个没有实现的模型类。如果它只是一个字段,那么接口不是更好的选择吗?您可以让一个类实现任意多个接口。如果要使用接口,我无法填充它,我需要一个现成的模型来获取/设置外部属性