Imitate multiple inheritance

Qwertiy

There is a class First and constructor function Second. I'm trying to create a class Both as a child of both of them. More accurate, I'm copiing methods from constructor function prototype to child class prototype.

I do understand that it's not the real inheritance, but that's enough for me.

There is other problem. How can I make typescript to accept copied methods?

class First {
  someMethod() {
    console.log('someMethod from First');
  }
}

function Second() {
  console.log('Second');
}

Second.prototype.doSmth = function () { 
  console.log('doSmth from Second');
}

interface IBoth {
  someMethod()
  doSmth()
}

class Both extends First /* implements IBoth */ {
  constructor() {
    console.log('constructor of Both');
    super();
    Second.call(this);
  }
}

for (let key in Second.prototype) {
  Both.prototype[key] = Second.prototype[key];
}

In fact I need to see the metods one level deepper:

class Final extends Both {
  doIt() {
    this.someMethod();
    //this.doSmth(); // How to make this call threated as correct?
    (this as any as IBoth).doSmth(); // That compiles, but it's awfull
  }
}

if in this case methods won't be visible in class Both, it's ok.

I've already tryed:

  1. When writing

    class Both extends First implements IBoth {
    

    typesctipt says that I haven't implement interface methods.

  2. Renaming Both to _Both and using

    var Both = _Both as typeof _Both;
    

    leaves same problems as original code, as First is never mentoned.

  3. If I rename Both to _Both and write

    var Both = _Both as typeof IBoth;
    

    typescript can't find IBoth.

Are there some other ways to reach it?


You can try at http://www.typescriptlang.org/Playground
Full code there

Add this line and run the code (copy code from right panel to your browser console):

(new Final).doIt();

Output when line this.doSmth(); is not commented:

constructor of Both
Second
someMethod from First
doSmth from Second
doSmth from Second

PS: Same question in Russian.

Louay Alakkad

Try this:

class Both extends First {
  constructor() {...}
  doSmth: typeof Second.prototype.doSmth;
}

Demo

It's also better to have Second as a class instead of a function. Add a declaration file if that's a javascript module.

Lastly, and if you can't have types for Second, just add types for each function like this:

class Both extends First {
  constructor() {...}
  doSmth: () => void;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related