facebook / prop-types

Runtime type checking for React props and similar objects
MIT License
4.48k stars 356 forks source link

Add generalized behavior #277

Closed nemzes closed 5 years ago

nemzes commented 5 years ago

prop-types is a great way to define object schemas, which would make it a suitable tool for writing tests, validating API data, etc. Since this could be shared with React component prop validation, it would be possible to reuse schemas in these disparate scenarios. In its current implementation, however, it's not easy to address those use-cases since the library is geared to provide in-browser feedback during development.

This PR introduces a PropTypes.generalize() function that changes the behaviour of the library to throw Errors instead of logging to the console. It also removes the "avoid duplicate messages" behaviour that exists for the benefit of human consumption. It should then be possible to validate arbitrary objects in automated workflows, e.g.:

import PropTypes from `prop-types`;

PropTypes.generalize();
const propTypes = ...
const dataObject = ...
try {
  PropTypes.checkPropTypes(propTypes, dataObject);
}
catch (err) {
  // Handle invalid data object
}
ljharb commented 5 years ago

You may be interested in the checkPropTypes function, which already allows you to use this library outside of react, with no changes needed.

nemzes commented 5 years ago

Ah… and now I feel dumb. It might be a good idea to add a link to that package in the README here 😁

ljharb commented 5 years ago

It is - see both "If you absolutely need to trigger the validation manually," and "If you DO want to use validation in production" in the readme.

nemzes commented 5 years ago

Uhmn, no…? The behaviour of PropTypes.checkPropTypes is still to log issues to the console. It's very awkward to use this is automated testing.

When you mentioned "You may be interested in the checkPropTypes function" I actually thought you were referring to this: https://github.com/ratehub/check-prop-types (which is what I think should be in the README). That package allows using its own checkPropTypes(), which does not rely on console for output.

I still need to see how to use this in production though.

ljharb commented 5 years ago

See #28 for that feature request.