I am currently in the process of creating an Event class with a data property that is typed based on the type of the event. Here is the code snippet I have been working on:
export interface EventTypes {
localeChange: {
locale: string;
};
translationsChange: undefined;
}
export default class Event<T extends keyof EventTypes> {
eventType: T;
data: EventTypes[T];
constructor(
eventType: T,
...data: EventTypes[T] extends undefined ? [] : [EventTypes[T]]
) {
this.eventType = eventType;
this.data = data[0];
}
}
My goal is to achieve the following functionalities:
- If the event type does not require any data (for example, "translationsChange"), the constructor should only take one argument and the data property for the instance should be set as undefined.
- If the event type demands additional data (such as "localeChange"), the constructor should accept 2 arguments with the data property of the instance having the specified type from
EventTypes
.
The code provided above generally works fine, but I am encountering a TypeScript error at the specific line mentioned below:
this.data = data[0];
Type 'EventTypes[T] | undefined' is not assignable to type 'EventTypes[T]'.
Type 'undefined' is not assignable to type 'EventTypes[T]'.
Type 'undefined' is not assignable to type 'never'.ts(2322)
When I modify the definition of the property to data?: EventTypes[T];
, the error disappears. However, it introduces the possibility of the property being undefined even for instances where the event type necessitates data.
I would greatly appreciate any guidance on how to properly type the data
property so that it aligns with the constructor and accurately reflects the definitions in EventTypes
.