Search code examples
node.jstypescripttypescript-genericsasync.js

(TS 2556) Why am I recieving a type error on a spread argument that has already been explicitly typed and passed as a rest parameter?


function debouncePromise<TParams extends Array<unknown>, TRes>(
fn: (a: TParams) => Promise<TRes>,
  time: number,
) {
  let timerId: ReturnType<typeof setTimeout> | undefined = undefined;

  return function debounced(...args: TParams) {
    if (timerId) {
      clearTimeout(timerId);
    }
    return new Promise((resolve) => {
      timerId = setTimeout(() => resolve(fn(...args)), time); //<= A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
    });
  };
}

I have already typed the spread argument in the function as a rest parameter. Why am I recieving an error on an argument/variable that has already been explicitly typed? How do I resolve this?

Update: tsplayground


Solution

  • Made a change in line 2 to fn: (...a: TParams) => and that resolved it!