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 eg
react-js-to-ts reactFile.js
The following example is taken from the projects website. A standard react component eg
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 });
}
}
Is there any tool that will help port the code
Nope. Either create one (and link back) or just do the manual work or just use any
to get a quick start 🌹
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.