【问题标题】:class hierarchy in TypeScriptTypeScript 中的类层次结构
【发布时间】:2017-10-20 14:55:58
【问题描述】:

我有以下类层次结构:

class BaseList {}

class SortableList extends BaseList {}

class EditableList extends BaseList {}

class EditableSortableList extends [Sotrable and Editable]

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

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

非常感谢任何帮助!

【问题讨论】:

  • 我很确定打字稿中没有多重继承。我建议你研究一下 mixins。

标签: angular typescript inheritance


【解决方案1】:

你应该检查Mixins in TypeScript

注意:重要的是要注意多重继承和混合都不是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];
        });
    });
}

【讨论】:

  • 感谢 mixins 为我工作得很好。我的情况比上面描述的要复杂一些 - 我有具有不同构造函数的通用抽象类,所以我不得不稍微改变它们,但最终我得到了我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多