TypeScript interface signature for the onClick event in ReactJS
Is there a way to replace the 'any' keyword in the IProps_Square interface with an explicit function signature
I would just () => void
i.e. a function that takes no arguments and you don't care if it returns anything.
import * as React from 'react';
import * as ReactDOM from 'react-dom';
interface IProps_Square {
message: string,
onClick: () => void,
}
class Square extends React.Component < IProps_Square > {
render() {
return (
<button onClick={this.props.onClick}>
{this.props.message}
</button>
);
}
}
class Game extends React.Component {
render() {
return (
<Square
message = { 'click this' }
onClick = { () => alert('hello') }
/>
);
}
}
ReactDOM.render(
<Game />,
document.getElementById('reactjs-tutorial')
);
However if you need the parameter the proper type for it is React.MouseEvent<HTMLElement>
, so:
interface IProps_Square {
message: string,
onClick: (e: React.MouseEvent<HTMLElement>) => void,
}
The interface with props should be
interface IProps_Square {
message: string;
onClick: React.MouseEventHandler<HTMLButtonElement>;
}
Notice also that if you use semicolons, the interface items separator is a semicolon, not a comma.