I have a piece of TypeScript code like this:
enum EventType {
EVENT_A = 'eventA',
EVENT_B = 'eventB',
... // more event types
}
interface Event {
type: EventType;
}
interface EventA extends Event {
type: EventType.EVENT_A;
data: PayloadForEventA;
}
interface EventB extends Event {
type: EventType.EVENT_B;
data: PayloadForEventB;
id: number;
}
... // More Event interfaces
Is it possible to somehow map the values of EventType to corresponding interfaces? If it could not be done automatically, is it possible to specify the types mapped by the enum values manually?
I do know that it is possible to map values to types as shown in this question. And using the method shown below, it could create the lookup table I needed:
type EventTypeLut = {
'eventA': EventA,
'eventB': EventB,
// ...
};
But this method hardcodes the value of enum into the LUT. The enum value might change in the future (which I don't have much control) and hardcoding the enum value makes it harder to maintain.
When I try to use EventType.EVENT_A as key name, TypeScript complains with "property or signature expected". Using template string seems also no avail. (It seems that the key name cannot be computed, even if it's a constant expression like 1+2.)
The reason I am trying to do this is I would like to create a typed EventEmitter with the enum value of EventType as name and respective typed object for callback function.
If there is a better way to achieve this, please also give a hint. Thanks in advance.