-
Notifications
You must be signed in to change notification settings - Fork 356
There should be a way to validate the "shape" of an array. #230
Comments
I'm confused; you want to validate that all items in an array match a validator? "shape" is for object properties, which arrays tend not to have. |
I want to be able to define validation for the elements of an array in a way that position matters. In my example an answer is a key / value array. An answer has the "shape" |
Ah, i see, you want to make a propType for a "tuple". I don't think it belongs in this project, but here's how you could do it using
(Arrays may be a special type of object, but conceptually they are quite different - arrays are lists, objects are bags of properties) |
Yes, a tuple is a good way to put it. This is the solution I came up with, before filing this ticket, which doesn't require adding the airbnb-prop-types library. function arrayOfShape(typeCheckers) {
return PropTypes.arrayOf(
(value, index, ...rest) => typeCheckers[index](value, index, ...rest)
)
} |
sure, that works as well (altho it won't check the length). |
Related to #143. |
Best version of preview example: function tuple(typeCheckers: Function[]) {
return PropTypes.arrayOf(
function (value, index, ...rest) {
return typeCheckers[index].call(PropTypes, value, index, ...rest);
}
)
} |
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 ashapeTypes
argument of either an object or an array.Example use case
Implementation wise, this should be as simple as updating the
for...in
loop increateShapeTypeChecker
to be afor...of
loop over theshapeTypes
entries.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.
The text was updated successfully, but these errors were encountered: