-
-
Notifications
You must be signed in to change notification settings - Fork 72
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
Allow event names to be numbers #96
Conversation
Also, FYI the issue linked in this comment here appears to have been shipped, so I can update this line to Line 167 in 3cf4a0a
|
👍 I think TS actually has built-in object key type you could use. |
Yeah, I'm ok with adding this. But can you add a short note that it's generally preferred to use symbols than numbers? |
There was already a note in the readme about the benefit of using symbols. I added the word "preferred" to it but wasn't sure what else I could add. Is it what you had in mind?
Nice! I pushed a commit replacing However now that I redefined Lines 105 to 110 in 3cf4a0a
I guess now that |
👍 |
👍 |
I pushed a commit to make it a runtime check. 👍 I added a second (boolean) param to Not really sure if this is the best way though. It means One idea I had to prevent any exploit was to change the param from a boolean to an internal (not publicly exported) symbol: const metaEventsAllowed = Symbol('metaEventsAllowed');
function assertEventName(eventName, allowMetaEvents) {
if (typeof eventName !== 'string' && typeof eventName !== 'symbol' && typeof eventName !== 'number') {
throw new TypeError('`eventName` must be a string, symbol, or number');
}
if (isListenerSymbol(eventName) && allowMetaEvents !== metaEventsAllowed) {
throw new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`');
}
} This way userland would never be able to bypass the error. I haven't worked with symbols much so I'm not sure whether this is a good pattern or not. wdyt? |
👍 That's a good use for symbols. |
Modified the runtime check to use a private symbol. 👌 I also added another commit renaming |
Thanks for the high-quality pull request 👍 |
Thanks @sindresorhus! 🎉 |
Hi 👋
I'd like to use emittery to model the packets sent between a client and server. All packets are identified by a "type", which is a number. Therefore I was hoping to use emittery in the following way:
This actually compiles fine, there's no type error. But at runtime an error is thrown here:
emittery/index.js
Lines 14 to 18 in 3cf4a0a
Maybe I'm missing something crucial here, but I don't see any harm in supporting numbers for event names? So I prepared this PR which does just that. Let me know what you think.
Thanks.