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

后端 未结 4 623
时光取名叫无心
时光取名叫无心 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:35

    import propTypes from 'prop-types';
    
    const nullable = propType => (props, propName, ...rest) =>
      props[propName] === null ? null : propType(props, propName, ...rest);
    
    const testMe = {
      a: 'string',
      b: 420,
      c: null,
      d: undefined,
      e: undefined
    };
    
    const testSchema = {
      a: nullable(propTypes.string.isRequired),
      b: nullable(propTypes.string.isRequired),
      c: nullable(propTypes.number.isRequired),
      d: nullable(propTypes.bool.isRequired),
      e: nullable(propTypes.number)
    };
    
    propTypes.checkPropTypes(testSchema, testMe, 'prop', 'testMe');
    // Warning: Failed prop type: Invalid prop `b` of type `number` supplied to `testMe`, expected `string`.
    // Warning: Failed prop type: The prop `d` is marked as required in `testMe`, but its value is `undefined`.
    

提交回复
热议问题