Is there a possibility to generate dynamic type that could substitute two parameters, for example, in
on: (eventName: EventName, callback: (data: any) => void) => void
, with something like on: (DynamicParams<EventName>) => void
, where it can retrieve the type of callback
from a predefined set and utilize it instead of the generic any
type?
I believe an easier explanation would involve some coding.
Let's assume I have an array containing different event types:
const events = ['loaded', 'changed'];
type ArrayElement<ArrayType extends readonly unknown[]> = ArrayType[number];
type EventName = ArrayElement<typeof events>
and a function that should only execute when a specific event notification is triggered;
const on = (eventName: EventName, callback: (data: any) => void) => {}
However, I want to be able to employ this function with callbacks that expect varying parameter types seamlessly, without manual type checks or casting, such as:
on('loaded', (list: Entry[]) => {
// perform actions on loaded array elements;
}
on('changed', (index: number) => {
// carry out tasks based on index of a changed entry;
}
Is there a method to devise a mapped type that would take EventName as input and yield a specific return type corresponding to each event?
Perhaps something along these lines:
const on(eventName: EventName, DynamicMethod<'eventName'> => void) => {}
const on(DynamicParams<'eventName'>) => {}
If we had to replace the event object and formulate a type in its stead:
type events = [
{
name: 'loaded',
method: (list: Entry[]) => void
},
{
name: 'changed',
method: (index: number) => void
}
]
Though uncertain about extracting the 'name' values instead of their types.