TypeScript equivalent of Java method references

3.3k Views Asked by At

I'm sort of new to TypeScript, I know Java quite well though. There, whenever a functional interface needs to be satisfied, it's most commonly done using lambda expressions (->) or method references (::).

Lambda expressions seem to be equivalent between the two languages (correct me if I'm wrong). Is there a way to make use of method references?

When the goal is to achieve this:

  this.entryService.getEntries()
    .subscribe(entries => this.listUpdateService.send(entries));

Is there a way to use a function reference? The following way of doing it appears to be errorous, because send isn't executed in the scope of this.listUpdateService. (BTW, which scope is it executed in?)

  this.entryService.getEntries()
    .subscribe(this.listUpdateService.send);
1

There are 1 best solutions below

0
On BEST ANSWER

You are right, the scope is not this.listUpdateService.

If you want to stick the correct scope, you normally use bind.

this.entryService.getEntries()
  .subscribe(this.listUpdateService.send.bind(this.listUpdateService));

Here is an example playground