facebook / prop-types

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

Ability to extend a PropTypes shape #314

Open luizpinheiro opened 4 years ago

luizpinheiro commented 4 years ago

I've seen some projects that define prop-types in separate files in order to reuse their definitions. The problem is that we can't extend prop-types definitions. Let's say we have a set of prop-types called Person.type.js:

export default PropTypes.shape({
    id: PropTypes.number,
    name: PropTypes.name,
})

The problem is that we can't do something like:

import PersonType from './Person.type.js'

export default PropTypes.shape({
    ...PersonType,
    someAdditionalProp: PropTypes.any
})

Also, exporting a plain object from 'Person.type.js' is not an option since we may want the ability to use those properties directly, and for the matter of consistency, we may not want to use it like PropTypes.shape(PersonType) (that would be a possible workaround) whenever we use the PersonType directly as a prop.

So would be great to have a method like PropTypes.extend(shape, additionalFields) so we could be able to write something like:

import PersonType from './Person.type.js'

export default PropTypes.extend(PersonType, {
    someAdditionalProp: PropTypes.any
})
ljharb commented 4 years ago

If you use and from https://npmjs.com/airbnb-prop-types, you can do and([shape1, shape2]) and combine them.