I try to create a dead-simple function that accepts:
- A callback
- An optional array of arguments to pass to the callback
The function in plain JS would look like this:
const callCallback = (cb, args = []) => cb(...args);
The callback might accept an arbitrary number of arguments & return whatever. The problem is that I can't properly express the type of callback with TypeScript. I tried to declare callCallback's type like this (the idea was to infer callback's arguments & return types):
export interface CallCallback {
<CbReturn, CbArgs>(
cb: (...optionalArguments: CbArgs[]),
args?: CbArgs[],
): CbReturn
};
However, this didn't work because it forces the callback to use arguments spreading syntax while it's not what I intend to do.
I also found this answer but as for now TS doesn't let me make spread argument optional.
How can I infer args number & types into cb parameters list?