How can I declare a PropType corresponding to a nullable number?

后端 未结 4 614
时光取名叫无心
时光取名叫无心 2021-02-02 05:26

I\'m looking for a PropType that means

\"this is required, and it will either be a number or be null\"

In other words,

4条回答
  •  别跟我提以往
    2021-02-02 05:45

    Currently prop-types library don't allow this. The way i get around this is using a custom validation function

    MyComponent.propTypes = {
      nullableArray: function(props, propName, componentName) {
        const { propName: data } = props;
    
        if (data === undefined) {
          return new Error(`Undefined ${propName} is not allowed`);
        }
    
        if (data !== null) {
          return; //this is allow when data is loading
        }
    
        if (!_.isArray(data)) {
          return new Error(`${propName} must be an array`);
        }
      }
    };

    You can make another step further to create a high order function to generate the validation function. this should get you started

    generateRequiredOrNullValidationFunction = expectedType => {
      if (expectedType !== "array") {
        return Error(`Unexpected ${expectedType}`);
      }
    
      return function(props, propName, componentName) {
        const { [propName]: data } = props;
    
        if (data === undefined) {
          return new Error(`Undefined ${propName} is not allowed`);
        }
    
        if (data !== null) {
          return; //this is allow when data is loading
        }
    
        if (expectedType === "array" && !_.isArray(data)) {
          return new Error(`${propName} must be an array`);
        }
      };
    };

    In this snippet, expectedType is a enumeration such as bool , array, number ...

提交回复
热议问题