TypeScript中的类层次结构

时间:2017-10-20 14:55:58

标签: angular typescript inheritance

我有以下类层次结构:

class BaseList {}

class SortableList extends BaseList {}

class EditableList extends BaseList {}

class EditableSortableList extends [Sotrable and Editable]

所以我想以某种方式继承/生成/混合Sotrable和Editable类到EditableSortableList,问题是如何?

here是用接口解决的类似问题,但接口无法解决代码重复问题我正在尝试解决构建此层次结构的问题。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

您应该检查Mixins in TypeScript

  

注意:重要的是要注意,多重继承和mixins都不是TypeScript中语言规范的一部分。 Mixins只是一种模式。

这样你可以拥有

class EditableSortableList implements SortableList, EditableList {
    //Properties and empty methods of both SortableList and EditableList only to satisfy the interfaces. They will be overridden in the next line.
}

applyMixins(EditableSortableList, [SortableList, EditableList]);

applyMixins辅助方法如下

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}
相关问题