Mebtte
Mebtte

Reputation: 149

How typescript has double generic of type?

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

Answers (1)

Tobias S.
Tobias S.

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

Playground

Upvotes: 1

Related Questions