Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript: How to invoke class function from anonymous function – property does not exist on type

There is a service is defined as below:

export class MyService {
    doSomething(callbacks: { onSuccess: (data: Object) => any, onError: (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
                },
                onError(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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What can be the possible reason?

>Solution :

Use an arrow function:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading