Leonardocregis
Leonardocregis

Reputation: 95

A Typed array of functions - using this reference

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 ??

Upvotes: 0

Views: 68

Answers (1)

artem
artem

Reputation: 51809

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

}

Upvotes: 1

Related Questions