My TypeScript code snippet looks 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
I am wondering if it is possible to map the values of EventType
to corresponding interfaces. If automatic mapping is not feasible, can I manually specify the types mapped by the enum values?
I am aware that values can be mapped to types as shown in this question. By using the method demonstrated below, a lookup table can be created:
type EventTypeLut = {
'eventA': EventA,
'eventB': EventB,
// ...
};
However, hardcoding the enum value into the LUT may cause maintenance issues if the enum value changes in the future (something beyond my control).
When attempting to use EventType.EVENT_A
as a key name, TypeScript throws an error with "property or signature expected". Even trying template strings does not seem to work. It appears that computed key names, even if constant expressions like 1+2
, are not allowed.
The reason for my attempt is to create a typed EventEmitter
where the enum value of EventType
serves as the name and the respective typed object for the callback function.
If there is a better approach to achieve this, please provide some guidance. Thank you in advance.