Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate PropTypes from TypeScript

I am using React with TypeScript. I am also using PropTypes. TypeScript is intended for compile time type checking while PropTypes validate passed props on run time (development mode). So I found myself writing types twice. Both TypeScript and PropTypes. For example, component ListingsList:

interface ListingsListProps {
    listings: Listing[];
    height: number;
    width: number;
    rowHeight: number;
    forwardedRef?: Ref<List>;
    className?: string;
}

const ListingsList: FunctionComponent<ListingsListProps> = props => {
...
...
};

ListingsList.propTypes = {
    listings: PropTypes.arrayOf(listingPropType.isRequired).isRequired,
    height: PropTypes.number.isRequired,
    width: PropTypes.number.isRequired,
    rowHeight: PropTypes.number.isRequired,
    forwardedRef: PropTypes.shape({ current: PropTypes.instanceOf(List).isRequired }),
    className: PropTypes.string,
};

Each time I made a mistake (defining a property differently in PropTypes and in TypeScript), I get typescript error. Sometimes I don't really know how to define the PropType. For example, when passing History property from 'history'. I don't want to define History PropType myself because it has a complicated shape. I saw there are projects that generates TypeScript from PropTypes but I really don't like it because TypeScript is much stronger, I can define more detailed types. I am looking for a way to generate PropTypes from TypeScript, and I think this is a must feature for React developers.

like image 747
Naor Avatar asked Nov 06 '22 12:11

Naor


1 Answers

You can use babel-plugin-typescript-to-proptypes. It requires either the @babel/plugin-syntax-jsx plugin or the @babel/preset-react preset.

Use npm install --save-dev babel-plugin-typescript-to-proptypes to install.

And here is a sample 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,
};
like image 136
Shayan Toqraee Avatar answered Nov 15 '22 04:11

Shayan Toqraee