I have a library of React components with defined proptypes and am considering switching to Typescript. Is there any tool that will help port the code? Here is an example set of props for a simple component:
static propTypes = {
active: PropTypes.bool,
children: PropTypes.node,
disabled: PropTypes.bool,
icon: Icon.propTypes.kind,
tabIndex: PropTypes.number
};
I'm imagining a tool that would convert this to something like:
interface IButtonProps {
active: boolean,
children: node,
disabled: boolean,
icon: Icon,
tabIndex: number
}
Not too hard to write, but it would be nice if it already existed.
You could use the react-javascript-to-typescript-transform package to automatically convert/port React JSX to Typescript TSX.
Code can be transformed via the CLI e.g.
react-js-to-ts reactFile.js
The following example is taken from the projects website. A standard react component e.g.
class MyComponent extends React.Component {
static propTypes = {
prop1: React.PropTypes.string.isRequired,
prop2: React.PropTypes.number,
};
constructor() {
super();
this.state = { foo: 1, bar: 'str' };
}
render() {
return (
<div>
{this.state.foo}, {this.state.bar}, {this.state.baz}
</div>
);
}
onClick() {
this.setState({ baz: 3 });
}
}
Would get converted to the following typescript file:
type MyComponentProps = {
prop1: string;
prop2?: number;
};
type MyComponentState = {
foo: number;
bar: string;
baz: number;
};
class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
constructor() {
super();
this.state = { foo: 1, bar: 'str' };
}
render() {
return (
<div>
{this.state.foo}, {this.state.bar}, {this.state.baz}
</div>
);
}
onClick() {
this.setState({ baz: 3 });
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With