How can I refer to a specific function argument right inside the function signature?
The image above is a fake just for demonstration! I provide name
and arg
and need to retrieve some type info for arg by stuffing name into another function. But I don't know how to refer to name inside the function signature.
Context:
I'm working on a simple event manager. You can define event-names, assign callbacks to those and fire events. Callbacks may have an arbitrary number of arguments.
(The example below is very reduced, the real implementation is more complex, e.g. events can have multiple callbacks etc)
type CallbackType = (...args: any[]) => void;
const eventRegistry: Map<string, CallbackType> = new Map();
const registerEvent = (name: string, callback: CallbackType): void => {
eventRegistry.set(name, callback);
}
const fireEvent = (name: string, ...args: any[]): void => {
eventRegistry.get(name)!(...args);
}
some example callbacks
const foo = (input: number): void => {
console.log("foo here:", input);
}
const bar = (input1: boolean, input2: string): void => {
console.log("bar here:", input1, input2);
}
event registration and event firing
registerEvent("someEventName", foo);
registerEvent("anotherEventName", bar);
fireEvent("someEventName", 42);
fireEvent("anotherEventName", true, "Hello World");
Here's a link to a typescript playground.
The implementation above is not type-safe. You don't get any hints in fireEvent
what arguments the callbacks expect.
So I tried using typescripts Parameters utility type:
const fireEvent = (name: string, ...args: Parameters<typeof eventRegistry.get(name)>): void => {
eventRegistry.get(name)!(...args);
}
But that got me nowhere. To correctly type args I first need to get the callback assigned to the event but I don't know how to refer to name.