I am currently working on a function that can take a function as input and return an "extended" function.
The returned function should have the same parameters as the original function, with an additional optional parameter at the end.
I have managed to reuse the parameters from the original function in the returned function, but I am struggling to add the extra optional parameter.
For example, consider the following code snippet (the logging scenario is just an example):
const asyncLog = async (log: string) => { /* ... */ };
function addLogging<T extends (...args: Parameters<T>) => ReturnType<T>>(fn: T, log: string) {
const fnWithLogging = async (...args: Parameters<T>, doLog = true) => {
if (doLog) await asyncLog(log);
return fn(...args);
};
return fnWithLogging;
}
const baseFn = async (a: number, b: string) => { /* ... */ };
const baseFnWithLogging = addLogging(baseFn, 'some log');
await baseFnWithLogging(1, '2', false);
The above code works, but I want to pass the parameters individually rather than as an array, like baseFnWithLogging(1, '2', false)
.
If I change
fnWithLogging(...args: Parameters<T>)
to fnWithLogging(...args: Parameters<T>)
, I encounter TypeScript error 1014 A rest parameter must be last in a parameter list.
.
Is there a way to achieve this functionality? Perhaps something like
extend<Parameters<T>, doLog = true>
?