how to create generic event handler with react typescript?

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top