1

I'm trying to make a type-helper where a known type can be inserted as a type parameter, and it's guaranteed to be correct. This way I can write EventHandler<MouseEvent> where I know that a MouseEvent will be the argument, and have the helper expand to (e: MouseEvent) => any for my convenience. See https://github.com/sdegutis/imlib/commit/f6a75a2c58bd4d8b5d134d446297b6fdbbbfb50d

Given

type Fn = <T extends Event>(e: T) => any;
const fn: Fn = (e: MouseEvent) => 3;

I get the error:

Type '(e: MouseEvent) => number' is not assignable to type 'Fn'.
  Types of parameters 'e' and 'e' are incompatible.
    Type 'T' is not assignable to type 'MouseEvent'.
      Type 'Event' is missing the following properties from type 'MouseEvent': altKey, button, buttons, clientX, and 23 more.(2322)

Playground link

But why? Shouldn't MouseEvent satisfy Event?

4
  • The caller chooses the generic function's type argument, not the implementer. A caller of an Fn can call it with a KeyboardEvent and then your implementation of fn might implode (of course, not if it just returns 3) as shown here. I don't know what you're trying to do, but maybe you want the type parameter to be on the type and not the call signature as shown here? Does that fully address the question? Or am I missing something? Commented Aug 18, 2024 at 17:36
  • @jcalz I've updated the question with more details. Commented Aug 18, 2024 at 18:34
  • Then you want to change the scope of the type parameter to be on the type and not the call signature as shown in this playground link (the same thing I linked in my prev comment). See the answers to the linked questions at the top of this post. Commented Aug 18, 2024 at 18:48
  • Yeah that fixes it. And it's what I had. I don't know why I thought it wasn't working. It works fine. IDE bug I guess. Commented Aug 18, 2024 at 19:07

0