Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

typescript - What does <Params extends any[]> generic type mean in TS

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)
  }
}
question from:https://stackoverflow.com/questions/65950374/what-does-params-extends-any-generic-type-mean-in-ts

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...