defineListenerShape<
EventName extends string,
EventData extends {
[key in EventName]: unknown;
}
> = <E extends EventName>(data: EventData[E]) => void;
enum EventName {
Click = 'click',
Hover = 'hover',
}
type EventDataMap = {
[EventName.Click]: number,
[EventName.Hover]: string,
}
type Listener = defineListenerShape<EventName, EventDataMap>;
type ClickListener = Listener<EventName.Click>;
The Listener
function above is generic, however TypeScript throws a Type 'Listener' is not generic
error. You can test and explore this scenario on the TypeScript playground.