-
Notifications
You must be signed in to change notification settings - Fork 476
Open
Labels
Description
Hi,
I want to define an events interface like so:
const events = {
test: (payload) => {
console.log(payload);
},
another: (payload) => {
console.log(payload);
}
} as const;so the event name is dynamic and can be added later on.
I defined the mitt emitter like so:
type EventName = keyof typeof events;
type Payload = { [key: string]: any };
type Events = { [key in EventName]: Payload };
export const analytics: Emitter<Events> = mitt<Events>();and now i can call the event function:
analytics.on("*", (type, payload) => {
const event = events[type];
event?.(payload);
});and this is works as expected:
analytics.emit("foo", { test: 1 }); // I get error on foo as it is not define in events objectHowever I cannot define an interface for events like so:
type EventsList = { [key: EventName]: (payload: Payload) => void };so i'll get the events list like so:
const events: EventsList = {
test: (payload) => {
console.log(payload);
},
another: (payload) => {
console.log(payload);
}
} as const;I get a ts error:
if i define it like this:
type EventsList = { [key: string]: (payload: Payload) => void };it doesn't enforce the event name.
here is a codesandbox:
https://codesandbox.io/s/aged-microservice-oi72gv?file=/src/index.ts:0-558
I'd appreciate any help, thanks.