How to prevent building app if component prop types are invalid?

后端 未结 3 1909
忘了有多久
忘了有多久 2021-02-19 06:08

Here is a example for PropTypes:

import PropTypes from \'prop-types\';

class Greeting extends React.Component {
  render() {
    return (
      

Hello,

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 07:02

    Your question arises from a misunderstanding of both the intent and implementation of PropTypes. PropTypes exists to provide configurable run-time validations of API usage. It does not perform static code analysis but rather validates usage at runtime.

    To provide additional context, the concept predates the mainstream usage of many static analysis tools. Furthermore, even with the introduction of these tools, some prefer runtime validation approaches. One reason for this could be to retain tool chain simplicity. PropTypes validation works in vanilla JavaScript without any additional tools or languages. However, since you are using JSX, and therefore already have a complex tool chain that involves multiple languages, this consideration is less relevant. However, another reason to use PropTypes is, if you are building a library, you can still provide a level of validation to your consumers without requiring them to use the same, or for that matter any, of the static analysis tools you've chosen.

    If you want to validate the correctness of your code before running it, you should use a static analysis tool. There are many options, and you may use multiple tools, but some examples include TypeScript, Flow, and Closure Compiler.

    Note that any of these static analysis options are, by definition, orthogonal to PropTypes and so may be used together with them freely. Therefore, I'm not suggesting that you abandon the use of PropTypes, but rather that you add a static analysis tool that caters to your use case.

提交回复
热议问题