0

I'm currently writing components using React & Typescript, and am coming up against an issue when it comes to tuple types (arrays with set types in set positions). Let's say for example I have a Component set up as follows:

interface Props {
    tuple: [string, number];
}

const Component: React.FunctionComponent<Props> = ({ tuple }) => <div>Component</div>;

Component.propTypes = {
    tuple: PropTypes.arrayOf([PropTypes.string, PropTypes.number]).isRequired,
};

This throws an error in Typescript, and understandably so because arrayOf is not the same as a tuple, since in arrayOf the string or number types can be anywhere within the array.

So to my question - is there any way of getting around using tuples with PropTypes? Either a solution using the existing types or some kind of custom function that will do the job. I've tried Googling but content in this area seems very thin on the ground, and the experiments I've attempted with my own custom PropTypes functions have been unsuccessful.

rwacarter
  • 1,915
  • 1
  • 14
  • 25
  • I would personally retire PropTypes altogether in a Typescript project. They are redundant and a not-particularly-effective way to achieve what Typescript already imposes. What's your reasoning for wanting to adopt PropTypes? – cefn May 07 '21 at 10:45
  • @cefn PropTypes offer runtime type-checking which Typescript will not do. They are for two separate uses, and not at all 'redundant': https://stackoverflow.com/questions/41746028/proptypes-in-a-typescript-react-application#:~:text=Typescript%20and%20PropTypes%20serve – rwacarter May 10 '21 at 10:59

1 Answers1

0

A suggestion was made in this React issue comment which indicates how you can specialise the type checking to take account of position, given the support for arrayOf to take a validation function (similar to map)...

https://github.com/facebook/prop-types/issues/230#issuecomment-431503477

function arrayOfShape(typeCheckers) {
  return PropTypes.arrayOf(
    (value, index, ...rest) => typeCheckers[index](value, index, ...rest)
  )
}
cefn
  • 2,895
  • 19
  • 28