score:2

Accepted answer

what you might think of as "broader" and "narrower" get reversed when dealing with callbacks. in order to assign a to b, where a and b are both callbacks, a has to accept all of the types that b accepts. if a only accepts a specific subset of what b does, then it's not assignable to b.

here, you have a type eventhandlechange that can handle the change on any htmlelement. the callback which you are trying to assign to it only accepts the change event for htmlinputelement, so it is not assignable.

one possible way to fix this is by moving the generic t higher up the chain so that we can say that buttonprops can take a very specific callback.

type handlechange = (value: string, checked: boolean, name: string) => void

type eventhandlechange<t extends htmlelement> = (
  event: react.changeevent<t>
) => void;

type change<t extends htmlelement> = handlechange | eventhandlechange<t>;

type buttonprops = {
  onchange?: change<htmlinputelement>
}

typescript playground link

score:0

in case you need a type that accepts any type of html element you can use:

type anyhtmlelement = htmlelementtagnamemap[keyof htmlelementtagnamemap]

if it comes from queryselector or ref you may need to add | null to the definition


Related Query

More Query from same tag