-
Notifications
You must be signed in to change notification settings - Fork 440
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[TypeScript] define events interface #163
Comments
Hi @alonronin , Could you solve your issue? |
@alonronin Hey, I stumbled upon this issue while working on my own bus and thought although you probably don't need this anymore it's an interesting exercise. Were you trying to define the schema in a single place, along with the handler implementation? Anyway, I think something like this does what you wanted, and should be easy to adjust to take in an interface type instead of the handlers: https://codesandbox.io/s/cool-leftpad-857rrd?file=/src/index.ts const events = {
withPrimitive: (payload: string) => {
console.log(payload);
},
withObject: (payload: { a: boolean }) => {
console.log(payload);
}
};
type EventSchema<T extends Record<string, (payload: any) => void>> = {
[K in keyof T]: Parameters<T[K]>[0];
};
type MittSchema = EventSchema<
typeof events & {
all: (payload: any) => any;
}
>;
export const bus: Emitter<MittSchema> = mitt<MittSchema>();
bus.emit("withPrimitive", "hello"); // pass
bus.emit("withPrimitive", 123); // fail |
@alonronin also stumbled upon this :) Getting back to the original example, it looks like there are 2 easy ways to solve this:
|
Hi,
I want to define an events interface like so:
so the event name is dynamic and can be added later on.
I defined the mitt emitter like so:
and now i can call the event function:
and this is works as expected:
However I cannot define an interface for events like so:
so i'll get the events list like so:
I get a ts error:
if i define it like this:
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.
The text was updated successfully, but these errors were encountered: