You can use ReactJS's components easily in TypeScript. Just rename the 'jsx' file 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) you must do a couple things:
1) convert React.createClass to an ES6 Class:
//helloMessage.tsx:
class HelloMessage extends React.Component {
render() {
return <div>Hello {this.props.name}</div>;
}
}
ReactDOM.render(<HelloMessage name="John" />, mountNode);
For more info on converting to ES6 look here
2) Add Props and State interfaces:
interface Props {
name:string;
optionalParam?:number;
}
interface State {
//empty in our case
}
class HelloMessage extends React.Component<Props, State> {
render() {
return <div>Hello {this.props.name}</div>;
}
}
// TypeScript will allow you to create without the optional parameter
ReactDOM.render(<HelloMessage name="Sebastian" />, mountNode);
// But it does check if you pass in an optional parameter of the wrong type
ReactDOM.render(<HelloMessage name="Sebastian" optionalParam='foo' />, mountNode);
Now TypeScript will display an error if the programmer forgets to pass props. Or if trying to pass in props that are not defined in the interface.