In our library, we have a collection of predefined actions, that can be run.
Instead of exposing these actions as part of the API, a single method shall be exposed to call the action, as we need to run some other independent actions aside the action itself (e.g. log the executed actions). But I'm currently stuck in the implementation of the actual action call. Below is the best I could do currently. Typescript is able to correctly suggest the arguments based on the passed handlerName to callHandler, but it fails at the spread parameter, complaining, that the argument is not a tuple. But the Parameters type returns a tuple, if I understand it correctly.
Please see the code below or in the typescript playground. Thanks for any hints in advance!
/**
* We have a predefined set of functions, with a fixed call signature.
* This is predefined in the Handlers type:
*/
type Handlers = {
add: {
handler: (argument: string) => string;
};
count: {
handler: (argument: number) => string;
}
};
const myHandlers : Handlers = {
add: {
handler: (argument: string) => `Add ${argument}`,
},
count: {
handler: (argument: number) => `I count to ${argument}`,
}
};
/**
* Now, we want to be able, to define a method, that proxies the calls to these functions (to do other checks upfront).
* How can this be typed safely?
*/
function callHandler<H extends keyof Handlers>(name: H, ...params: Parameters<Handlers[H]["handler"]>) {
return myHandlers[name].handler(...params);
}
// Example call:
console.log(callHandler("count", 10));