小编jun*_*ray的帖子

打字稿中的安全类型去抖函数

我在打字稿中有以下去抖功能:

export function debounce<T>(
  callback: (...args: any[]) => void,
  wait: number,
  context?: T,
  immediate?: boolean
) {
  let timeout: ReturnType<typeof setTimeout> | null;

  return (...args: any[]) => {
    const later = () => {
      timeout = null;

      if (!immediate) {
        callback.apply(context, args);
      }
    };
    const callNow = immediate && !timeout;

    if (typeof timeout === "number") {
      clearTimeout(timeout);
    }

    timeout = setTimeout(later, wait);

    if (callNow) {
      callback.apply(context, args);
    }
  };
}

Run Code Online (Sandbox Code Playgroud)

我正在寻找一种更好的方法来 ...args: any[] 使用更安全的类型进行转换。

我怎样才能改变它?

更新

我想出了这个解决方案:

export function debounce<T …
Run Code Online (Sandbox Code Playgroud)

types debouncing typescript

5
推荐指数
1
解决办法
2875
查看次数

标签 统计

debouncing ×1

types ×1

typescript ×1