1

I am JS developer and currently scratching surface with TS.

I was looking for implementation of debounce with TS when I went to this question: Typescript debounce function not calling function passed as parameter

So this is the snippet for reference

function debounce<Params extends any[]>(
  func: (...args: Params) => any,
  timeout: number,
): (...args: Params) => void {
  let timer: NodeJS.Timeout
  return (...args: Params) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args)
    }, timeout)
  }
}

function test(message) {
  alert(message);
}

const debouncedTest = debounce(test, 2000);

debouncedTest('message');

Here, I am not sure what does this line mean

<Params extends any[]>

As per my understanding of Generics type in typescript, We use Generic type when we don't know what would be the input/return type

For example, from this example

interface Lengthwise {
  length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length); // Now we know it has a .length property, so no more error
  return arg;
}

We know that arg is going to have property length but anyway, I am unable to comprehend what does Params extends any[]> mean.

[Update:] For debounce (snippert above), is this a valid implementation?

function debounce (func: (...args:any[]) => any, timeout:number):(...args: any[]) => void {
let timer: any
return (...args: any[]) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args)
    }, timeout)
  }
}
  • Does this answer your question? [What does 'extends' actually mean in typescript?](https://stackoverflow.com/questions/55354313/what-does-extends-actually-mean-in-typescript) – jonrsharpe Jan 29 '21 at 07:40
  • Generics is used here to preserve original function signature in resulting function (will accept same arguments). Constraint `extends any[]` is used because rest parameter type must be an array – Aleksey L. Jan 29 '21 at 07:40
  • @jonrsharpe thanks, the answer was nicely written but I wasn't able to connect dots which could help me in finding answer for my question. – James Steven Jan 29 '21 at 07:56
  • @AlekseyL. Can you please explain `Generics is used here to preserve original function signature in resulting function`? or if you could write more detailed answer? – James Steven Jan 29 '21 at 07:58
  • 1
    What do you mean is it a valid implementation? What you started with is *already* an implementation, not just a type. – jonrsharpe Jan 29 '21 at 09:13

0 Answers0