Menu

React, etc. Tech Stack

React, Flux, GraphQL, Hack, HHVM...? All of this and more!

Automatic React PropTypes to TypeScript Conversion

React and TypeScript are an effective combination, but since the React is developed by Facebook in Flow (their strongly typing JavaScript technique), it's not always as easy as it could be.

To smooth working with the two Uber competitor Lyft has generated a tool that automatically generates TypeScript code from React components.

Started at Facebook, the React.js library is now use across the online industry. This has only accelerated after patent woes were quenched by MIT licensing. TypeScript has followed a similar trend. Coming from Microsoft, it's now a common sight everywhere - it's even an officially accepted language at Google.

React has a built in typing system called prop types, which is an effective way of defining properties components can receive. However, this is somewhat cumbersome and exclusive to React. TypeScript on the other hand provides a clean type annotation syntax for JavaScript.

Type conversion example snippets

This is fastest described by looking at example components, with PropTyped React components going in:

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

The outcoming converted code provides valid TypeScript, complete with optional PropTypes converted to equivalent parameters:

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

The development of the has been dormant since July of 2017, but that is not a warning site as both React and TypeScript are stable technologies. There are few backwards breaking changes en these, which allows this reliable type conversion tool to be generated at all.

To get started, look at the quick start guide on the TypeScript project page on GitHub: https://github.com/lyft/react-javascript-to-typescript-transform

Written by Jorgé on Wednesday January 17, 2018

Permalink -

« Prisma is a database agnostic GraphQL API layer for Node.js - CSS Modules arrive to Create React App (CRA) in version 2.0 »