从TypeScript生成PropTypes

问题描述 投票:1回答:1

我正在将React与TypeScript一起使用。我也在使用PropTypes。TypeScript用于编译时类型检查,而PropTypes在运行时(开发模式)验证传递的props。所以我发现自己两次写类型。 TypeScript和PropTypes。例如,组件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,
};

每次我犯了一个错误(在PropTypes和TypeScript中以不同的方式定义属性),我都会遇到打字稿错误。有时我真的不知道如何定义PropType。例如,从“ history”传递History属性时。我不想自己定义History PropType,因为它的形状很复杂。我看到有一些从PropTypes生成TypeScript的项目,但我真的不喜欢它,因为TypeScript更强大,我可以定义更详细的类型。我正在寻找一种从TypeScript生成PropTypes的方法,并且我认为这是React开发人员的必备功能。

javascript reactjs typescript react-proptypes
1个回答
0
投票

您可以使用babel-plugin-typescript-to-proptypes。它需要@babel/plugin-syntax-jsx插件或@babel/preset-react预设。

使用npm install --save-dev babel-plugin-typescript-to-proptypes进行安装。

这是示例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,
};
© www.soinside.com 2019 - 2024. All rights reserved.