prop-types icon indicating copy to clipboard operation
prop-types copied to clipboard

There should be a way to validate the "shape" of an array.

Open GreenGremlin opened this issue 7 years ago • 7 comments

It would be useful to have the ability to define the "shape" of an array prop. This could fairly easily be done by refactoring PropTypes.shape to take a shapeTypes argument of either an object or an array.

Example use case

const answers = loadAnswers();
/*
loadAnswers returns an array of key / value pairs.
[
  ['name', 'Foo Bar'],
  ['email', '[email protected]'],
  ['website', 'www.foo.com'],
];
*/
<UserForm answers={answers} />

UserForm.propTypes = {
  answers: PropTypes.arrayOf(PropTypes.shape([
    PropTypes.oneOf(['name', 'email', 'website']),
    PropTypes.string,
  ])),
}

Implementation wise, this should be as simple as updating the for...in loop in createShapeTypeChecker to be a for...of loop over the shapeTypes entries.

-       if (propType !== 'object') {
+       if (propType !== 'object' && propType !== 'array') {
          return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
        }
-       for (var key in shapeTypes) {
+       for (var [key, checker] of Object.entries(shapeTypes)) {
-         var checker = shapeTypes[key];

Of course this assumes support for Object.entries and destructuring, which I'm not sure this package is free to use. If not, then the implementation will be a little more complex, but certainly doable.

If this seems like a reasonable proposal, I can put up a PR.

GreenGremlin avatar Oct 19 '18 19:10 GreenGremlin