Skip to main content

The difference between PropTypes.oneOf and PropTypes.oneOfType

I'm hoping this little note will help some of the JavaScript React developers that are using the PropTypes module. These two PropTypes are easily confused. For some reason, oneOf always comes to mind when I should be using oneOfType.

Without further ado, here's the difference:

'oneOf' is like an enum #

Use PropTypes.oneOf if you want the prop value to be one of a specific set:

MealComponent.propTypes = { dinner: PropTypes.oneOf(['steamed clams', 'steamed hams']) };

'oneOfType' is like a union type #

Use PropTypes.oneOfType if you want to say a prop is of type X or type Y. For example, a number or a string:

MealComponent.propTypes = { dinnerId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), };

In both cases, the options are passed as an array. I hope this quick reminder is helpful to some of you. Happy coding.