最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to write a debounce which return exactly the same type as the passed function in typescript? - Stack Overflow

programmeradmin5浏览0评论

I hope that the debounce function can realize that the type of the returned function is exactly the same as the type of the passed function (whose return value is void or Promise<void>). I have write the following code

type VoidFunction = (...args: any[]) => void;
type PromiseVoidFunction = (...args: any[]) => Promise<void>;
export function debounce<T extends VoidFunction>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void;

export function debounce<T extends PromiseVoidFunction>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => Promise<void>;
export function debounce<T extends(VoidFunction | PromiseVoidFunction)>(fn: T, delay: number) {
  let timer: number | null = null;
  return function (this: ThisParameterType<T>, ...args: Parameters<T>): Promise<void> | void {
    if (timer) {
      clearTimeout(timer);
    }
    if (fn.constructor.name === 'AsyncFunction') {
      return new Promise<void>((resolve) => {
        timer = setTimeout(() => {
          timer = null;
          Promise.resolve(fn.apply(this, args)).then(resolve);
        }, delay);
      });
    }
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, delay);
  };
};

However, when I use this debounce and passed a function has a Promise<void>return type, typescript still infers the return type of the returned function as void

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论