What should be the correct TypeScript interface signature for the onClick event in ReactJS?

What should be the correct TypeScript interface signature for the onClick event in ReactJS?

I’m converting a ReactJS tutorial from JavaScript to TypeScript and have the following interface:

interface IProps_Square {  
  message: string,  
  onClick: any,  
}  

I want to replace the any type for onClick with a more explicit function signature. How should I properly define the onClick event type in TypeScript for a React component? Any suggestions would be greatly appreciated.

Try to use React.MouseEventHandler :

import React from 'react';

interface IProps_Square {
  message: string;
  onClick: React.MouseEventHandler<HTMLButtonElement>;
}

This approach uses React.MouseEventHandler to define the click event handler for a button (HTMLButtonElement). It’s the most common and concise way in React.

Explicit Function Signature for onClick :

interface IProps_Square {
  message: string;
  onClick: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
}

Here, the onClick function is explicitly typed to accept a React.MouseEvent with the proper generic types. It’s useful if you need to access event properties directly in your function.

Using React.EventHandler Type for Flexibility :

interface IProps_Square {
  message: string;
  onClick: React.EventHandler<React.MouseEvent<HTMLButtonElement>>;
}

This approach uses the React.EventHandler type to define the event handler. While less commonly used, it’s still a valid and flexible way to handle events in TypeScript for React.