Error in 'this' in a typescript function

2

I'm having an 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 not pass this to const context the following error appears:

  

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

    
asked by anonymous 25.05.2018 / 14:55

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 context , and passed null to the function inside apply

    
25.05.2018 / 15:49
0

The problem is being caused because your this is not linked to an object, but it can represent anything in that context. If you want to give the possibility of having a this linked 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); 
      } 
   } 
}
    
01.06.2018 / 20:34