javascript - 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.
解决方案
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,
};
推荐阅读
- raku - 具有可变数量 Real 参数的脚本
- javascript - 如何确保 material-ui 中的整个 Button 组件为 onClick 事件返回相同的 ID 值?
- c++ - 编译时检查 C++ 中结构的更改
- javascript - clean-webpack-plugin 和 file-loader 的 CSS URL 问题
- android - 如何远程在 react-native-push-notifications 中设置自定义声音
- email - 当没有任何工作时,如何从 mac 终端发送邮件?
- plot - 为什么在尝试绘制参数图时,Maxima 在 plot2d 上给我一个错误?
- google-apps-script - 如何根据值更改范围保护?
- javascript - 多表问题的 Qualtrics 动态总和
- c++ - 初始化语句条件表达式 C++