在打字稿中反应 useCallback

时间:2021-02-05 07:36:04

标签: reactjs typescript react-hooks

类型错误:'Function' 类型的参数不可分配给类型 '(...args: any[]) any 的参数

类型 'Function' 不匹配签名 '(...args: any[]): any'。

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

我已经尝试添加

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

添加道具前 enter image description here

但它不起作用。请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我在 .jsx 文件上遇到过这个问题,我认为这只会发生在非 tsc 文件的 tsx? 编译中(但不确定)。此外,奇怪的一点是,VSCode 并没有将其检测为错误。

无论如何,问题很明显,这是因为 lodash/debounce 返回了 DebouncedFunc,如下面的签名所示:

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

要解决此问题,您可以尝试以下两件事:

  • 禁用该去抖动调用的 ts 检查,即在 debounce() 函数调用上方添加以下注释
useCallback(
 // @ts-ignore
 debounce(),
 []
);
  • 更好的方法,而不是完全忽略 ts-checks 是,将函数分离到不同的实例中:
const debounceFn = debounce(...);
const callback = useCallback((...args) => debounceFn(...args), []);

我希望这能解决您的问题。