Jake Pearson
Jake Pearson

Reputation: 27757

Convert jsx to tsx?

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.

Upvotes: 11

Views: 36139

Answers (2)

Ben Smith
Ben Smith

Reputation: 20240

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

Upvotes: 10

basarat
basarat

Reputation: 276353

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 🌹

Upvotes: 0

Related Questions