Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  135] [ 5]  / answers: 1 / hits: 143922  / 5 Years ago, wed, january 30, 2019, 12:00:00

The official reactjs.org website contains an excellent introductory tutorial.



The tutorial snippets are written in JavaScript and I am trying to convert these to TypeScript.



I have managed to get the code working but have a question about using interfaces.



What should the correct function signature be for the onClick callback.



Is there a way to replace the 'any' keyword in the IProps_Square interface with an explicit function signature ?



Any help or suggestions would be really appreciated, many thanks Russell



index.html



<!DOCTYPE html>
<html lang=en>
<body>
<div id=reactjs-tutorial></div>
</body>
</html>


index.tsx



import * as React from 'react';   
import * as ReactDOM from 'react-dom';

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

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')
);

More From » reactjs

 Answers
44

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.


Another hint: I recommend type rather than interface for props. They are almost the same, the only difference I found is that interface may be extended anywhere in the code, in fact it is used for globals.


[#52689] Thursday, January 24, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
;