Home > Mobile >  Typescript: How to invoke class function from anonymous function - property does not exist on type
Typescript: How to invoke class function from anonymous function - property does not exist on type

Time:11-27

There is a service is defined as below:

export class MyService {
    doSomething(callbacks: { onSuccess: (data: Object) => any, one rror: (err: any) => any }) {
        // This function does something
    }
}

It is used in a component as below:

export class MyComponent implements OnInit {
    someFunction(): void { 
        this.myService.doSomething(
            {
                onSuccess(data: Object) {
                    onSuccessFunction(data) // Error here
                },
                one rror(err: any) {
                }
            }
        )
    }
    
    onSuccessFunction(data: Object) {
    }
}

As can be seen above, the onSuccessFunction which is defined in MyComponent and invoked in the anonymous function onSuccess. But still typescript is giving error as below:

Property 'initActiveOrders' does not exist on type '{ onSuccess: (data: Object) => any; one rror: (err: HttpErrorResponse) => any; }'.ts(2339)

What can be the possible reason?

CodePudding user response:

Use an arrow function:

someFunction(): void { 
  this.myService.doSomething({
    onSuccess: (data: Object) => {
      this.onSuccessFunction(data);
    },
    ...
  });
}

CodePudding user response:

It looks like you forgot to add this. before the method-call on line 5

  • Related