I am attempting to develop an interceptor function, specifically a throttle function.
Let's look at this example:
function throttle(func: Function, wait: number = 0): Function {
let previous: {
args: any[];
timestamp: number;
result: any;
} = {
args: [],
timestamp: 0,
result: null
};
return (...currentArgs: any[]): any => {
const now = Date.now();
const remaining = wait && (wait - (now - previous.timestamp));
const argumentsChanged = JSON.stringify(currentArgs) !== JSON.stringify(previous.args);
if (argumentsChanged || (wait && (remaining <= 0 ||remaining > wait))) {
previous = {
args: currentArgs,
timestamp: now,
result: func.apply(this, currentArgs)
};
}
return previous.result;
};
}
This function first executes the argument-passed function and will not call it again until either the specified wait time has been reached or the arguments for the target function have changed.
The issue arises when trying to ensure that the returned function type matches the input function, allowing for transparency to the caller.
For example, while the following should be permissible, it is currently not working as intended:
function updateStatus(id: number, newStatus: string): void {
// ...
}
// ...
// Type 'Function' is not assignable to type '(id: number, newStatus: string) => void'
this.updateStatus = throttle(this.updateStatus.bind(this), 500);
So, how can I effectively accomplish this?