Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript / ReactJS / setTimeout: 'this' implicitly has type 'any' because it does not have a type annotation.ts

In my NextJS/React typescript app I'm using a setTimeout.

There is a bug in React apps causing setTimeout's to get called instantly, which I then found a fix in this answer here: ReactJS: setTimeout() not working?

Below is my code, but I'm getting the following typescript error on the this on this.resetNotification

any 'this' implicitly has type 'any' because it does not have a type annotation.ts(2683) Board.tsx(158, 7): An outer value of 'this' is shadowed by this container.

@bind
resetNotification(): any {
  console.log('resetNotification...');
  this.setState({ notificationClass: 'spin-in-notification' });
  this.props.setNotification('', false);
}

@bind
private handleNotificationClick() {
  this.setState({ notificationClass: 'slide-out-bck-top' });

  setTimeout(
    function() {
      this.resetNotification();
    }
    .bind(this),
    500
  );
}

enter image description here

like image 620
Leon Gaban Avatar asked Mar 21 '26 06:03

Leon Gaban


2 Answers

Do it with arrow function on setTimeout for heredate parents props

setTimeout(
  () => {
  this.resetNotification();
  }......
like image 89
Jordi Castillo Avatar answered Mar 23 '26 20:03

Jordi Castillo


If you still want to use function () {} syntax, you can pass this as the first parameter to the function, along with a type annotation. Like this:

  setTimeout(
    function(this: Board) {
      this.resetNotification();
    }
    .bind(this),
    500
  );

I'm assuming since the file is called Board.tsx that your component is <Board>. If not, change the type annotation for this.

like image 39
sleighty Avatar answered Mar 23 '26 19:03

sleighty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!