• Stars
    star
    366
  • Rank 116,547 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Generate React PropTypes from TypeScript interfaces or type aliases.

babel-plugin-typescript-to-proptypes

Build Status npm version npm deps

A Babel plugin to generate React PropTypes from TypeScript interfaces or type aliases.

This plugin DOES NOT support converting props who's type information is referenced in another file, as Babel as no access to this information, and we do not run TypeScript's type checker.

Examples

Supports class components that define generic props.

// Before
import React from 'react';

interface Props {
	name?: string;
}

class Example extends React.Component<Props> {
	render() {
		return <div />;
	}
}

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

class Example extends React.Component {
	static propTypes = {
		name: PropTypes.string,
	};

	render() {
		return <div />;
	}
}

Function components that annotate the props argument. Also supports anonymous functions without explicit types (below).

// Before
import React from 'react';

interface Props {
	name: string;
}

function Example(props: Props) {
	return <div />;
}

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

function Example(props) {
	return <div />;
}

Example.propTypes = {
	name: PropTypes.string.isRequired,
};

And anonymous functions that are annotated as a React.SFC, React.FC, React.StatelessComponent, or React.FunctionComponent.

// Before
import React from 'react';

type Props = {
	name?: string;
};

const Example: React.FC<Props> = (props) => <div />;

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

const Example = (props) => <div />;

Example.propTypes = {
	name: PropTypes.string,
};

Requirements

  • Babel 7+
  • TypeScript 3+

Installation

yarn add --dev babel-plugin-typescript-to-proptypes
// Or
npm install --save-dev babel-plugin-typescript-to-proptypes

Usage

Add the plugin to your Babel config. It's preferred to enable this plugin for development only, or when building a library. Requires either the @babel/plugin-syntax-jsx plugin or the @babel/preset-react preset.

// babel.config.js
const plugins = [];

if (process.env.NODE_ENV !== 'production') {
  plugins.push('babel-plugin-typescript-to-proptypes');
}

module.exports = {
  // Required
  presets: ['@babel/preset-typescript', '@babel/preset-react']
  plugins,
};

When transpiling down to ES5 or lower, the @babel/plugin-proposal-class-properties plugin is required.

Options

comments (boolean)

Copy comments from original source file for docgen purposes. Requires the comments option to also be enabled in your Babel config. Defaults to false.

module.exports = {
	plugins: [['babel-plugin-typescript-to-proptypes', { comments: true }]],
};
// Before
import React from 'react';

interface Props {
	/** This name controls the fate of the whole universe */
	name?: string;
}

class Example extends React.Component<Props> {
	render() {
		return <div />;
	}
}

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

class Example extends React.Component {
	static propTypes = {
		/** This name controls the fate of the whole universe */
		name: PropTypes.string,
	};

	render() {
		return <div />;
	}
}

customPropTypeSuffixes (string[])

Reference custom types directly when they match one of the provided suffixes. This option requires the type to be within the file itself, as imported types would be automatically removed by Babel. Defaults to [].

module.exports = {
	plugins: [['babel-plugin-typescript-to-proptypes', { customPropTypeSuffixes: ['Shape'] }]],
};
// Before
import React from 'react';
import { NameShape } from './shapes';

interface Props {
	name?: NameShape;
}

class Example extends React.Component<Props> {
	render() {
		return <div />;
	}
}

// After
import React from 'react';
import { NameShape } from './shapes';

class Example extends React.Component {
	static propTypes = {
		name: NameShape,
	};

	render() {
		return <div />;
	}
}

forbidExtraProps (boolean)

Automatically wrap all propTypes expressions with airbnb-prop-types forbidExtraProps, which will error for any unknown and unspecified prop. Defaults to false.

module.exports = {
	plugins: [['babel-plugin-typescript-to-proptypes', { forbidExtraProps: true }]],
};
// Before
import React from 'react';

interface Props {
	name?: string;
}

class Example extends React.Component<Props> {
	render() {
		return <div />;
	}
}

// After
import React from 'react';
import PropTypes from 'prop-types';
import { forbidExtraProps } from 'airbnb-prop-types';

class Example extends React.Component {
	static propTypes = forbidExtraProps({
		name: PropTypes.string,
	});

	render() {
		return <div />;
	}
}

implicitChildren (bool)

Automatically include a children prop type to mimic the implicit nature of TypeScript and React.ReactNode. Defaults to false.

module.exports = {
	plugins: [['babel-plugin-typescript-to-proptypes', { implicitChildren: true }]],
};
// Before
import React from 'react';

interface Props {
	foo: string;
}

class Example extends React.Component<Props> {
	render() {
		return <div />;
	}
}

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

class Example extends React.Component {
	static propTypes = {
		foo: PropTypes.string.isRequired,
		children: PropTypes.node,
	};

	render() {
		return <div />;
	}
}

mapUnknownReferenceTypesToAny (boolean)

By default unknown reference types are omitted from the generated prop types. Sometimes though it might be necessary to keep the prop in the generated prop types. In this case the prop type would be any.

Defaults to false.

module.exports = {
	plugins: [['babel-plugin-typescript-to-proptypes', { mapUnknownReferenceTypesToAny: true }]],
};
// Before
import React from 'react';

interface Props<T> {
	as?: T;
}

class Example<T> extends React.Component<Props<T>> {
	render() {
		return <div />;
	}
}

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

class Example extends React.Component {
	static propTypes = {
		as: PropTypes.any,
	};

	render() {
		return <div />;
	}
}

maxDepth (number)

Maximum depth to convert while handling recursive or deeply nested shapes. Defaults to 3.

module.exports = {
	plugins: [['babel-plugin-typescript-to-proptypes', { maxDepth: 3 }]],
};
// Before
import React from 'react';

interface Props {
	one: {
		two: {
			three: {
				four: {
					five: {
						super: 'deep';
					};
				};
			};
		};
	};
}

class Example extends React.Component<Props> {
	render() {
		return <div />;
	}
}

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

class Example extends React.Component {
	static propTypes = {
		one: PropTypes.shape({
			two: PropTypes.shape({
				three: PropTypes.object,
			}),
		}),
	};

	render() {
		return <div />;
	}
}

maxSize (number)

Maximum number of prop types in a component, values in oneOf prop types (literal union), and properties in shape prop types (interface / type alias). Defaults to 25. Pass 0 to disable max.

module.exports = {
	plugins: [['babel-plugin-typescript-to-proptypes', { maxSize: 2 }]],
};
// Before
import React from 'react';

interface Props {
	one: 'foo' | 'bar' | 'baz';
	two: {
		foo: number;
		bar: string;
		baz: boolean;
	};
	three: null;
}

class Example extends React.Component<Props> {
	render() {
		return <div />;
	}
}

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

class Example extends React.Component {
	static propTypes = {
		one: PropTypes.oneOf(['foo', 'bar']),
		two: PropTypes.shape({
			foo: PropTypes.number,
			bar: PropTypes.string,
		}),
	};

	render() {
		return <div />;
	}
}

strict (boolean)

Enables strict prop types by adding isRequired to all non-optional properties. Disable this option if you want to accept nulls and non-required for all prop types. Defaults to true.

module.exports = {
	plugins: [['babel-plugin-typescript-to-proptypes', { strict: true }]],
};
// Before
import React from 'react';

interface Props {
	opt?: string;
	req: number;
}

class Example extends React.Component<Props> {
	render() {
		return <div />;
	}
}

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

class Example extends React.Component {
	static propTypes = {
		opt: PropTypes.string,
		req: PropTyines.number.isRequired,
	};

	render() {
		return <div />;
	}
}

More Repositories

1

interweave

🌀 React library to safely render HTML, filter attributes, autowrap text with matchers, render emoji characters, and much more.
TypeScript
1,048
star
2

emojibase

🎮 A collection of lightweight, up-to-date, pre-generated, specification compliant, localized emoji JSON datasets, regex patterns, and more.
TypeScript
443
star
3

decoda

A lightweight lexical string parser for BBCode styled markup.
PHP
196
star
4

uploader

[Deprecated] A CakePHP plugin for file uploading and validating.
PHP
193
star
5

packemon

📦 Build and prepare packages for npm distribution using standardized configurations and practices. Gotta pack 'em all!
TypeScript
188
star
6

forum

[Deprecated] A CakePHP plugin for forum / bulletin board systems.
PHP
131
star
7

boost

🚀 A collection of type-safe cross-platform packages for building robust server-side and client-side systems.
TypeScript
105
star
8

shapeshifter

🐺 Generate relational schemas, PropTypes, Flow aliases, and TypeScript interfaces from JSON or GraphQL schematic files.
TypeScript
103
star
9

utility

[Deprecated] A CakePHP plugin for common utility classes.
PHP
69
star
10

docusaurus-plugin-typedoc-api

Docusaurus plugin that provides source code API documentation powered by TypeDoc.
TypeScript
63
star
11

admin

[Deprecated] A CakePHP plugin that provides admin CRUD functionality for app and plugin models.
PHP
47
star
12

auto-login

[Deprecated] Use the Utility plugin.
PHP
45
star
13

transit

A lightweight file uploading library with image transformation and remote storage support.
PHP
41
star
14

type-converter

[Deprecated] Convert a type to another.
PHP
31
star
15

feeds

[Deprecated] Use the Utility plugin.
PHP
30
star
16

tournament

[Deprecated] A CakePHP plugin for competitive leagues, tournaments, brackets, teams and players.
PHP
24
star
17

optimal

Build, validate, and transform values with immutable typed schemas.
TypeScript
17
star
18

rut

⚛️ React testing made easy. Supports DOM and custom renderers.
TypeScript
16
star
19

spam-blocker

[Deprecated] Use the Utility plugin.
PHP
15
star
20

build-tool-config

Build tool configuration files for easy re-use.
TypeScript
12
star
21

formation

[Unsupported] A stand alone form manager, builder, validator and cleaner.
PHP
11
star
22

compression

[Unsupported] A stand alone CSS parser, minifier and cacher.
PHP
10
star
23

ajax-handler

[Deprecated] Use the Utility plugin.
PHP
10
star
24

rust-js-ecosystem

Rust crates for common JavaScript and TypeScript functionality.
Rust
7
star
25

gears

[Unsupported] A stand alone PHP template engine and parser.
PHP
6
star
26

resession

[Unsupported] A stand alone session management class.
PHP
5
star
27

databasic

[Deprecated] Use the Titon\Model package.
PHP
5
star
28

rust-cicd-env

Rust crates for extracting CI/CD information from the environment.
Rust
4
star
29

numword

[Unsupported] A stand alone number to word converter.
PHP
3
star
30

milk

A fork of MooTools for the new generation.
JavaScript
3
star
31

blizzard-sdk

PHP SDK for the Blizzard WoW API
PHP
3
star
32

dotfiles

Dotfiles for my local environment.
Vim Script
3
star
33

data-structures

A collection of JavaScript data structures.
JavaScript
3
star
34

compartment

A component dependency graph.
JavaScript
2
star
35

typescript-eslint-single-run

TypeScript
2
star
36

packager

[Deprecated] A dependency and script packager for static assets.
PHP
1
star
37

web-lang

A programming language for the web.
1
star
38

hhi

Command line tool for generating Hack HHI definitions.
PHP
1
star
39

statsburner

[Deprecated] A stand alone wrapper for the Feedburner Awareness API.
PHP
1
star
40

joop

OOP based functionality for JavaScript and Node.js
JavaScript
1
star
41

figg

Powerful configuration format, for all languages.
1
star
42

aoc-2022

Advent of Code 2022
Rust
1
star