Michał Lis
Michał Lis

Reputation: 531

Default implementation of method in interface

Is there any way to make default implementation of method in interface? I cannot make it in a baseclass unfortunately. I feel this is pretty easy question, but cannot find the right solution for a quite long moment.

/edit In my example I need something like this:

class A {
  somePropertyA;
  someFunctionA() {
    console.log(this.somePropertyA);
  }
}
class B {
  somePropertyB;
  someFunctionB() {
    console.log(this.somePropertyB);
  }
}
class C {
  // Here we want to have someFunctionA() and someFunctionB()
  // without duplicating code of this implementation.
}

The solution of B entends A and C extends B is for me a not so optimal.

Upvotes: 16

Views: 19278

Answers (1)

jcalz
jcalz

Reputation: 329553

No. Interfaces don't exist at runtime, so there's no way to add runtime code such as a method implementation. If you post more specifics about your use case, a more specific or helpful answer may be possible.

EDIT:

Ah, you want multiple inheritance which you can't do with classes in JavaScript. The solution you are probably looking for is mixins.

Adapting the example from the handbook:

class A {
    somePropertyA: number;
    someFunctionA() {
        console.log(this.somePropertyA);
    }

}

class B {
    somePropertyB: string;
    someFunctionB() {
      console.log(this.somePropertyB);
    }

}

interface C extends A, B {}
class C { 
    // initialize properties we care about
    somePropertyA: number = 0;
    somePropertyB: string = 'a';   
}
applyMixins(C, [A, B]);

const c = new C();
c.someFunctionA(); // works
c.someFunctionB(); // works        

// keep this in a library somewhere    
function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            derivedCtor.prototype[name] = baseCtor.prototype[name];
        });
    });
}

That should work for you. Maybe eventually this can be done less painfully with decorators, but for now the above or something like it is probably your best bet.

Upvotes: 14

Related Questions