[TypeScript] define events interface
- Dominant language
- TypeScript
- Stars
- 11.9k
- Forks
- 488
- PR merge metrics
- No merged PRs in 30d
Description
Hi,
I want to define an events interface like so:
```ts
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:
```ts
type EventName = keyof typeof events;
type Payload = { [key: string]: any };
type Events = { [key in EventName]: Payload };
export const analytics: Emitter = mitt();
```
and now i can call the event function:
```ts
analytics.on("*", (type, payload) => {
const event = events[type];
event?.(payload);
});
```
and this is works as expected:
```ts
analytics.emit("foo", { test: 1 }); // I get error on foo as it is not define in events object
```
However I cannot define an interface for events like so:
```ts
type EventsList = { [key: EventName]: (payload: Payload) => void };
```
so i'll get the events list like so:
```ts
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:
```ts
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.
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.