我有以下类层次结构:
class BaseList {}
class SortableList extends BaseList {}
class EditableList extends BaseList {}
class EditableSortableList extends [Sotrable and Editable]
所以我想以某种方式继承/生成/混合Sotrable和Editable类到EditableSortableList,问题是如何?
here是用接口解决的类似问题,但接口无法解决代码重复问题我正在尝试解决构建此层次结构的问题。
非常感谢任何帮助!
答案 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];
});
});
}