0

I have following class hierarchy:

class BaseList {}

class SortableList extends BaseList {}

class EditableList extends BaseList {}

class EditableSortableList extends [Sotrable and Editable]

So I'd like to inherit/produce/mix somehow Sotrable and Editable classes into EditableSortableList, the question is how?

here is similar problem solved with interfaces, but interfaces do not solve code duplication issue I'm trying to solve building this hierarchy.

Any help is highly appreciated!

Roman Hutnyk
  • 1,549
  • 9
  • 14
  • I'm pretty sure there is no multiple inheritance in typescript. I would suggest you look into mixins. – toskv Oct 20 '17 at 15:03

1 Answers1

3

You should check Mixins in TypeScript

Note: Is important to notice that neither multiple inheritance nor mixins are part of the language specification in TypeScript. Mixins here is just a pattern.

This way you can have

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]);

With applyMixins helper method being the following

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}
Carlos Muñoz
  • 17,397
  • 7
  • 55
  • 80
  • 1
    thank you mixins worked well for me. My case was a bit more complex, than described above - I have generic abstract classes with different constructors, so I had to change them a bit, however finally I've got what I was looking for! – Roman Hutnyk Oct 24 '17 at 05:48