0

I'm trying to create a interface that defines the a interface with a array of functions and a this guard as below:

interface MyInterface {
  myFunctions: ((this:MyInterface, somevar: string): void)[];
}

But , when i try to use it as below:

class Myclass implements MyInterface {
  myFunctions: ((this:Implementation, somevar: string): void)[];
  useFunction (): void {
    this.myFunctions[0](somevar);
  }
}

The erro below happens Class 'Myclass ' incorrectly implements interface 'MyInterface'

Somebody knows how i do implements that ??

1
  • Your class implementation is different from your interface, so that's not allowed. I'm also not sure how an interface can have a function that implements itself .... Commented Nov 7, 2017 at 14:11

1 Answer 1

1

First of all, function type is declared with => , not :

interface MyInterface {
  myFunctions: ((this:MyInterface, somevar: string) => void)[];
}

Second, why do you have this:Implementation in the class, not this.MyClass or this.MyInterface as declared in the interface? It should be consistent - either this.Implementation in the both class and interface, or this.MyInterface in the interface and this.MyClass in the class.

Then, in javascript (and typescript), for calling a function and setting it's this context the function name must be followed immediately by (, for example this.useFunction().

You have this.myFunctions[0](somevar) which means that you are calling the first element of myFunctions as free function, without setting its this context. You need to set this explicitly using call() here:

interface MyInterface {
  myFunctions: ((this:MyInterface, somevar: string) => void)[];
}

class Myclass implements MyInterface {
    myFunctions: ((this: Myclass, somevar: string) => void)[] = [];


    useFunction(somevar: any): void {
        this.myFunctions[0].call(this, somevar);
    }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help, the first error about how the function is declared was just my bad, it was like you said in the original source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.