andywer / typed-emitter

🔩 Type-safe event emitter interface for TypeScript
MIT License
268 stars 24 forks source link

Variable event names #17

Closed spencercap closed 2 years ago

spencercap commented 2 years ago

hey @andywer 👋 thanks a million for this project!

i put together what you proposed in #15 as i needed dynamic event names for a project. it's a breaking change since the typed events are defined differently but do whatcha want.

spencercap commented 2 years ago

ah! actually, this approach breaks the strict typing a bit. you are able to mix and match the event names and typed handler functions. for example, i get no type errors doing:

type MessageEvents =
    | EmitterEvent<`foo:${string}`, (size: number, strict: boolean) => void>
    | EmitterEvent<`bar:${string}`, (force: boolean) => void>
        | EmitterEvent<'test', () => void>;

bus.emit('foo:one'); // TS is okay with this... because it is assuming we are using the 'test' handler function which doesnt require arguments
andywer commented 2 years ago

Thanks a lot, @spencercap!

You are right, but it feels as if there must be a better way. Still playing with it myself.

andywer commented 2 years ago

Superseded by #23, I guess?

andywer commented 2 years ago

Closing. Feel free to re-open / complain if this PR is still relevant.

Thanks for the contribution, though! Not all code gets merged, but it helped move the discussion forward 👍