SimpleGuy
SimpleGuy

Reputation: 2894

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:

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

What can be the possible reason?

Upvotes: 0

Views: 97

Answers (2)

pzaenger
pzaenger

Reputation: 11973

Use an arrow function:

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

Upvotes: 1

Cheteel
Cheteel

Reputation: 46

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

Upvotes: 0

Related Questions