Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property 'bind' does not exist on type 'void'

I have the following code:

setInterval(this.CheckIfCameraIsAvailable(false).bind(this), 2 * 60 * 1000);

 private CheckIfCameraIsAvailable(forceCheck: boolean) {

}

I have the following error:

Property 'bind' does not exist on type 'void'

The error will be solved when I remove (forceCheck: boolean) parameter from (CheckIfCameraIsAvailable) function, but I want to pass a parameter to the function.

like image 852
Ala Avatar asked Dec 18 '22 04:12

Ala


1 Answers

In your example, you are accidentally calling the function, and then trying to use .bind on the result. The correct long-hand code would be the following (where you pass the false argument as part of the bind:

class Example {
  CheckIfCameraIsAvailable(forceCheck: boolean) {
    alert(forceCheck);
  }

  run() {
    setInterval(this.CheckIfCameraIsAvailable.bind(this, false), 2000);
  }
}

const example = new Example();
example.run();

The short-hand way to preserve the lexical scope is to use an arrow function:

class Example {
  CheckIfCameraIsAvailable(forceCheck: boolean) {
    alert(forceCheck);
  }

  run() {
    setInterval(() => this.CheckIfCameraIsAvailable(false), 2000);
  }
}

const example = new Example();
example.run();

And this is the equivalent of introducing an intermediate variable like this:

class Example {
  CheckIfCameraIsAvailable(forceCheck: boolean) {
    alert(forceCheck);
  }

  run() {
    const _this = this;
    setInterval(function () { _this.CheckIfCameraIsAvailable(false) }, 2000);
  }
}

const example = new Example();
example.run();
like image 182
Fenton Avatar answered Jan 01 '23 18:01

Fenton