Reputation: 149
type ListenerShape<
EventType extends string,
EventTypeMapData extends {
[key in EventType]: unknown;
}
> = <E extends EventType>(data: EventTypeMapData[E]) => void;
enum EventType {
A = 'a',
B = 'b',
}
type EventTypeMapData = {
[EventType.A]: number,
[EventType.B]: string,
}
type Listener = ListenerShape<EventType, EventTypeMapData>;
type AListener = Listener<EventType.A>;
Above Listener
is a generic function, but typescript throw Type 'Listener' is not generic
error. Here is the playground.
Upvotes: 0
Views: 233
Reputation: 23795
"Above Listener
is a generic function" - that is somewhat true. Listener
is a type that contains a generic function. The type itself it not generic though. So calling Listener<EventType.A>
does not work.
You could use the following workaround:
const func: Listener = null!
type AListener = typeof func<EventType.A>;
// type AListener = (data: number) => void
Upvotes: 1