facebook / prop-types

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

Fix silently failing invalid validators in shape #234

Closed asbjornh closed 5 years ago

asbjornh commented 5 years ago

Fixes #220 Possibly also #181

This PR adds type checks for validators in createShapeTypeChecker and createStrictShapeTypeChecker so that they can fail loudly on invalid validators and everyone can be safe and happy! 😊

As outlined in #220 , providing any falsy value instead of a validator will cause validation to be skipped, meaning invalid props won't be caught. Providing a truthy value that's not a function results in a caught but displayed javascript error Warning: Failed prop type: checker is not a function which is better than nothing but not really that helpful.

The most likely cause of issues is typos in validator names, like PropTypes.boolean (which I've since discovered that I've written several times). As mentioned in #220 this is mitigated by using eslint-plugin-react/no-typos, but I do feel that relying on a third party that's not a dependency is more of a band-aid than a solution.

Another cause would be references to internal or external things that might or might not be functions, which is not caught by the eslint plugin.

const validator = false;
Component.propTypes = {
  foo: PropTypes.shape({ bar: validator })
};
ljharb commented 5 years ago

@gaearon do you think this is a bug fix, or a breaking change because it might introduce additional warnings?

asbjornh commented 5 years ago

@ljharb In hindsight I think the tests might be a little thin. I'd be happy to add some more invalid cases in both tests unless that's too late now (I don't fully understand what you did with with those force pushes)

ljharb commented 5 years ago

@asbjornh definitely not too late! i rebased the PR branch; after a git fetch locally you can git reset --hard origin/fix-invalid-validators-in-shape, or git checkout master && git branch -D fix-invalid-validators-in-shape && git checkout fix-invalid-validators-in-shape, or you can delete and re-clone your local repo.

asbjornh commented 5 years ago

Great! Thanks :)

asbjornh commented 5 years ago

@ljharb I've added some more test cases (which was good because I discovered an issue). I think this is ready now, unless you guys want any changes :)

asbjornh commented 5 years ago

Yay!