ljharb/prop-types-tools

[feature request] forbidInnerExtraProps

mqklin opened this issue · 8 comments

This validator validates all inner props.
For example:

static propTypes = forbidExtraProps({
  firstLevelProp: PropTypes.shape({
    secondLevelProp: PropTypes.string,
  }),
});

<ThisComponent
  qwe // will warn
  firstLevelProp={{
    rty: true, // won't warn
  }}
/>

But

static propTypes = forbidInnerExtraProps({
  firstLevelProp: PropTypes.shape({
    secondLevelProp: PropTypes.string,
  }),
});

<ThisComponent
  qwe // will warn
  firstLevelProp={{
    rty: true, // will warn too
  }}
/>

What happens if you do:

static propTypes = forbidExtraProps({
  firstLevelProp: PropTypes.shape(forbidExtraProps({
    secondLevelProp: PropTypes.string,
  })),
});

?

Its a bit verbose, and doesn't work for this (redux-form just for example):

import myPropTypes from '../someProptypes';
import { propTypes as reduxFormPropTypes } from 'redux-form';
...
static propTypes = forbidExtraProps({
  ...myPropTypes,
  ...reduxFormPropTypes,
});

In your example, forbidExtraProps will certainly combine myPropTypes and reduxFormPropTypes, and forbid anything beyond those - I'm not sure how your example is relevant to your shape question tho.

I mean reduxFormPropTypes can also have shapes, and I can't add forbidExtraProps into it.

Well sure - you can't modify shapes you didn't create. The forbidding has to happen at shape creation time - in other words, redux-form would have to add it.

Yes, but if I have forbidInnerExtraProps validator, I just

static propTypes = forbidInnerExtraProps({
  ...reduxFormPropTypes,
});

and it would work.

That wouldn't really be possible. forbidExtraProps works by adding a hidden propType that checks to ensure that only the specified props exist - it'd have to recursively dig down, find PropTypes.shape, figure out what the object literal originally was (which shape does not expose, so it's not possible here) and then recreate a new shape. This also wouldn't work using Shape from react-validators, for example.

It simply has to be done at shape creation time.

Ah, ok. Thank you for the response.