FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

[TypeScript] define events interface · Issue #163 · developit/mitt · GitHub

/ mitt Public

[TypeScript] define events interface #163

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 object

However 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


    Back | FazBrowse Home | New Git URL