I am interested in implementing a debounce function using TypeScript. Below is the code snippet I have written:
function debounce(fn: Function, time: number): Function {
// ...
}
However, my eslint
is flagging an issue with using Function
as a type. Here is the original text:
Avoid using Function
as a type. The Function
type can accept any function-like value.
This lack of type safety when calling the function can lead to common bugs. It may also allow things like class declarations, which will throw errors at runtime if they are not called with new
.
If you need the function to accept specific arguments, it's recommended to explicitly define the function shape.
This seems to be causing an issue, any suggestions?
==================== Some update ==================================
If I were to use JavaScript instead, my code would look like this:
function debounce(fn, time) {
let timer
return function (...args) {
clearTimeout(timer)
timer = setTimeout(() => fn(...args), time)
}
}