Actually you can use ReactJS's components in Typescript as in facebook's example. Just replace 'jsx' file's extension to 'tsx':
//helloMessage.tsx:
var HelloMessage = React.createClass({
render: function() {
return <div>Hello {this.props.name}</div>;
}
});
ReactDOM.render(<HelloMessage name="John" />, mountNode);
But in order to make full use of Typescript's main feature (static type checking) should be done couple things:
1) convert React.createClass example to ES6 Class:
//helloMessage.tsx:
class HelloMessage extends React.Component {
render() {
return <div>Hello {this.props.name}</div>;
}
}
ReactDOM.render(<HelloMessage name="John" />, mountNode);
2) next add Props and State interfaces:
interface IHelloMessageProps {
name:string;
}
interface IHelloMessageState { //empty in our case } class HelloMessage extends React.Component {
constructor(){
super();
}
render() {
return
<div>Hello {this.props.name}</div>;
}
}
ReactDOM.render(, mountNode);
Now Typescript will display an error if the programmer forgets to pass props. Or if they added props that are not defined in the interface.
References:
ReactJSNotesForProfessionals Book
Top comments (0)