Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content
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

snabb bind: type improvement for eventname and event callback #16808

Merged
merged 1 commit into from
Jan 21, 2025

Conversation

allanjoseph98
Copy link
Member

No description provided.

export function bind(eventName: string, f: (e: Event) => any, redraw?: Redraw, passive = true): Hooks {
export function bind<K extends keyof GlobalEventHandlersEventMap>(
eventName: K,
f: (ev: GlobalEventHandlersEventMap[K]) => any,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the K generic for? I would think

export function bind(
  eventName: keyof GlobalEventHandlersEventMap,
  f: (ev: GlobalEventHandlersEventMap[typeof eventName]) => any,
  ...

because if a K instance is disjoint from the keys in GlobalEventHandlersEventMap, then the function argument constraint for f will not be satisfied and it's a compile tile failure.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using the generic <K> with extends constrains the type to keys of GlobalEventHandlersEventMap. K cannot be disjoint from those keys. If you were to try bind('schlawg', ....) you would get

Argument of type '"schlawg"' is not assignable to parameter of type 'keyof GlobalEventHandlersEventMap'.

Using the generic, we know that e in

bind('submit', e => e.submitter)

is of type SubmitEvent and that it has the submitter property.
Your alternative also works, but then we lose the narrowing for the function. It is treated as the union type of all the values of GlobalEventHandlersEventMap (UIEvent | MouseEvent | SubmitEvent ....)

Copy link
Collaborator

@schlawg schlawg Jan 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i get it now, thanks. some wires got crossed in my thinking of extends (like it was & or something)

@ornicar ornicar merged commit 5b16bda into lichess-org:master Jan 21, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants