preactjs / preact-router

:earth_americas: URL router for Preact.
http://npm.im/preact-router
MIT License
1.01k stars 156 forks source link

Pass generic to HTMLAttributes in Link typings #445

Closed vpzomtrrfrt closed 1 year ago

vpzomtrrfrt commented 1 year ago

Seems to fix type errors with event listeners

rschristian commented 1 year ago

Can you show an example of what this fixes?

vpzomtrrfrt commented 1 year ago

Here's an example:

function onClickTrackingLink(evt: preact.JSX.TargetedEvent<HTMLAnchorElement>) {
    console.log("Clicked on link with href", evt.currentTarget.href);
}

function TrackingLink(props: preact.JSX.HTMLAttributes) {
    return <Link {...props} onClick={onClickTrackingLink} />;
}

This fails with

Type '(evt: TargetedEvent<HTMLAnchorElement, Event>) => void' is not assignable to type 'EventHandler<TargetedMouseEvent<EventTarget>>'.
  Types of parameters 'evt' and 'event' are incompatible.
    Type 'TargetedMouseEvent<EventTarget>' is not assignable to type 'TargetedEvent<HTMLAnchorElement, Event>'.
      Type 'TargetedMouseEvent<EventTarget>' is not assignable to type '{ readonly currentTarget: HTMLAnchorElement; }'.
        Types of property 'currentTarget' are incompatible.
          Type 'EventTarget' is missing the following properties from type 'HTMLAnchorElement': charset, coords, download, hreflang, and 305 more.

because the type for onClick isn't specific enough. The event handler parameter needs to be this so that currentTarget is correctly typed as HTMLAnchorElement.