Ankit
Ankit

Reputation: 59

React useCallback in typescript

Type error: Argument of type 'Function' is not assignable to parameter of type '(...args: any[]) any

Type 'Function' provides no match for the signature '(...args: any[]): any'.

 const handleImageSearch = useCallback(
 debounce((value) => searchUnsplashImage(value), 400),
   ^
  [],
 );

I have tried adding the

interface IFunction {
  (...argArray: any[]): any;
}
const handleImageSearch = useCallback<IFunction>(
 debounce((value) => searchUnsplashImage(value), 400),
   ^
  [],
 );

Befor adding props enter image description here

But it does not work. Please help me with this.

Upvotes: 0

Views: 2718

Answers (1)

phoenisx
phoenisx

Reputation: 1689

oneI have been facing this issue on .jsx files, and I assume this happens only for tsc compilations for non tsx? files (not sure, though). Also, the weird point is, this is not getting detected by VSCode as an error.

Anyways, the issue is quite clear, it happens because lodash/debounce returns a DebouncedFunc, as can be seen in the below signature:

debounce<T extends (...args: any) => any>(func: T, wait?: number, options?: DebounceSettings): DebouncedFunc<T>;

To get around this you can try one of the followings:

  • Disable ts check for that debounce call, i.e. add the following comment above debounce() function call
useCallback(
 // @ts-ignore
 debounce(),
 []
);
  • Better way, instead of ignoring ts-checks completely is to, separate the function into a different instance:
const debounceFn = debounce(...);
const callback = useCallback((...args) => debounceFn(...args), []);
  • Or even more concise:
const callback = useCallback((...args) =>
  debounce((param1, paramN) => {
    /** Your Function Body */
  })(...args)
, []);

Obviously, this is a workaround, and adds more code. For me // @ts-ignore seems like a better option.

A much better solution would be to override React Types itself for useCallback, details: How to overwrite incorrect TypeScript type definition installed via @types/package, but that's all a personal preference.

I hope this fixes your issue.

Upvotes: 1

Related Questions