Search code examples
reactjsreact-proptypes

Difference between PropTypes.exact and PropTypes.shape


What's the difference between

PropTypes.exact({
  name: PropTypes.string,
  age: PropTypes.number
})

vs

PropTypes.shape({
  name: PropTypes.string,
  age: PropTypes.number
})

I will be glad of any help


Solution

  • Basically exact will give you a warning if your prop object contains extra property not mentioned while declaring it through PropTypes.exact({ }).

      // An object taking on a particular shape
      optionalObjectWithShape: PropTypes.shape({
        color: PropTypes.string,
        fontSize: PropTypes.number
      }),
    
      // An object with warnings on extra properties
      optionalObjectWithStrictShape: PropTypes.exact({
        name: PropTypes.string,
        quantity: PropTypes.number
      }), 
    

    Reference: https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes