facebook / prop-types

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

Use Parent type inside it #246

Closed AhmedElywa closed 5 years ago

AhmedElywa commented 5 years ago

Hello ,

i need to use same parent type inside it like typescript

in typeScript you can say interface Parent { title: string, children: [Parent] | Parent[] }

now to use like this with PropTypes `

const itemType = { title: PropTypes.string.isRequired, replace: PropTypes.bool, prefetch: PropTypes.bool, expanded: PropTypes.bool, group: PropTypes.bool, hidden: PropTypes.bool, home: PropTypes.bool, icon: PropTypes.string, target: PropTypes.string, url: PropTypes.string }

Menu.propTypes = { items: PropTypes.arrayOf( PropTypes.shape({ ...itemType, children: PropTypes.arrayOf( PropTypes.shape({ ...itemType, children: PropTypes.arrayOf( PropTypes.shape({ ...itemType }) ) }) ) }) ) }

` any idea to use it in easy way

thank you

ljharb commented 5 years ago

Are you asking about making recursive propTypes?

AhmedElywa commented 5 years ago

yes need like this

ljharb commented 5 years ago

Typically you’d do this by creating a custom propType function, but it’s pretty rare to need this.

Something like:

function recursive(...args) {
  return PropTypes.oneOfType([
    PropTypes.arrayOf(recursive),
    PropTypes.shape({
      ...itemType,
      children: recursive,
    }),
  ])(...args);
};
Foo.PropTypes = {
  items: recursive,
};
AhmedElywa commented 5 years ago

Thank you this work very good for me

function recursive(...args) {
  return PropTypes.arrayOf(
    PropTypes.shape({
      ...itemType,
      children: recursive
    })
  )(...args);
}