Search code examples
reactjseslintreact-proptypes

PropTypes : PropTypes.array VS PropTypes.arrayOf(PropTypes.any)


Consider this :

import PropTypes from 'prop-types';

[...]

Component.propTypes = {
  someProp: PropTypes.array,
}

and :

import PropTypes from 'prop-types';

[...]

Component.propTypes = {
  someProp: PropTypes.arrayOf(PropTypes.any),
}

The first will make eslint trigger error in editor :

Prop type 'array' is forbidden eslint(react/forbid-prop-types)

However, they both will trigger the same error if condition is not respected, and according to the documentation, it should behave the exact same way.

Is there any difference between those two validations ?

(And can I ignore this error ?)


Solution

  • I guess the difference is

    PropTypes.array scans for

    • array of objects [{name:'ABC'},{name:'XYZ'}]
    • array of strings ['Lorem','Ipsum']
    • array of integers [2,4,66,4]
    • array of nested arrays [['d'],[[{name:'a'},{name:'b'}]]]
    • array of functions [foo,bar]

    and much more

    Whereas for PropTypes.arrayOf would accept parameters that which type of values would be inside array. Like more strict rule

    PropTypes.arrayOf(PropTypes.number) scans for only

    • array of integers [2,4,66,4] because you mentioned PropTypes.number

    and would show warning/error if there was another data type

    Same goes for every primitive(integers, strings) and non-primitive types(objects,functions,arrays)

    Like PropTypes.arrayOf(PropTypes.string) scans for

    • array of strings ['Lorem','Ipsum']

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