Error in this in a typescript function

Asked

Viewed 59 times

2

I have error in the function below:

export const throttle = (func: Function, limit: number) => {
   let inThrottle: boolean;
   return function () {
      const args = arguments;
      const context = this;
      if (!inThrottle) {
         func.apply(context, args);
         inThrottle = true;
         setTimeout(() => inThrottle = false, limit);
      }
   }
}

I can’t get past the this to the const context appears the following error:

[ts] 'this' implicitly has type 'any' because it does not have a type Annotation.

  • We did not write [SOLVED] in the title, as you yourself arrived at the solution, you will have to mark your answer as the right answer. You may have to wait 48 hours to release this option for you

  • I tried to do this but without success. The following message appears: You cannot vote for your post

2 answers

2

*********SOLUTION***************

export const throttle = (func: Function, limit: number) => { 
   let inThrottle: boolean; 
   return function () { 
      const args = arguments; 
      if (!inThrottle) { 
         func.apply(null, args); 
         inThrottle = true; 
         setTimeout(() => inThrottle = false, limit); 
      } 
   } 
}

I removed the context, and passed null to the function inside the apply

0

The problem is being caused because your this is not tied to an object, but it can represent anything in that context. If you want to give the possibility of having a this linked to the function you should expect the scope to be passed by argument.

export const throttle = (func: Function, limit: number, scope: Object = null) => { 
   let inThrottle: boolean; 
   return function () { 
      const args = arguments; 
      if (!inThrottle) { 
         func.apply(scope, args); 
         inThrottle = true; 
         setTimeout(() => inThrottle = false, limit); 
      } 
   } 
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.