Babel Plugin: TypeScript to PropTypes

2.1.0 · active · verified Sun Apr 19

babel-plugin-typescript-to-proptypes is a Babel plugin designed to automatically generate React PropTypes from TypeScript interfaces and type aliases within your React components. This tool is particularly useful for projects that want to leverage TypeScript for type safety during development while still providing runtime PropTypes for environments that rely on them (e.g., older React versions, certain testing setups, or for debugging purposes). The current stable version is 2.1.0, and it maintains an active release cadence with frequent updates for Babel and TypeScript compatibility. A key differentiator is that it operates solely on the Babel AST, meaning it does not run TypeScript's type checker and therefore cannot resolve type information referenced from external files. It integrates directly into your Babel build pipeline.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a simple React functional component with a TypeScript interface, showing the input code that the plugin transforms into code with `PropTypes`. The Babel configuration snippet shows how to enable the plugin, typically outside of production builds.

import React from 'react';
import PropTypes from 'prop-types';

interface MyComponentProps {
  /** A required string prop */
  name: string;
  count?: number;
  isActive: boolean;
}

function MyComponent(props: MyComponentProps) {
  return (
    <div>
      <p>Hello, {props.name}</p>
      {props.count && <p>Count: {props.count}</p>}
      {props.isActive ? <p>Active</p> : <p>Inactive</p>}
    </div>
  );
}

// babel.config.js (config for the plugin)
// This quickstart demonstrates the *before* and *after* for the plugin.
// To actually run the plugin, you'd need a Babel setup.
// Add this to your Babel configuration's plugins array:
// plugins: [
//   '@babel/preset-typescript',
//   '@babel/preset-react',
//   process.env.NODE_ENV !== 'production' && ['babel-plugin-typescript-to-proptypes', { comments: true }],
// ].filter(Boolean),

// Expected output after plugin execution (simplified):
// MyComponent.propTypes = {
//   /** A required string prop */
//   name: PropTypes.string.isRequired,
//   count: PropTypes.number,
//   isActive: PropTypes.bool.isRequired,
// };

export default MyComponent;

view raw JSON →