What prop type should I check for requiring the source?

AmerllicA picture AmerllicA · Oct 9, 2018 · Viewed 9.6k times · Source

I'm writing a project based on react native. I'm using prop-types for type checking of components. now I wanna wrap Image component of react-native in my own Image component. In the following code see my own Image component:

import React from 'react';
import { Image as ImageNative } from 'react-native';
import PropTypes from 'prop-types';

const Image = ({ style, source }) => (
  <ImageNative source={source} style={style} />
);

Image.defaultProps = {
  style: {}
};

Image.propTypes = {
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  source: PropTypes.any.isRequired
};

export default Image;

Each place I decide to use my own Image component, I will import it and use it like below:

<Image source={require('assets/images/splashSignInAsset.png')} />

Actually, I checked source prop inside my own Image component as any.

source: PropTypes.any.isRequired

But it's not true. I know it. I don't know what should I write there. What is the type of require function return value which I checked it here?

Answer

AmerllicA picture AmerllicA · Oct 14, 2018

Actually, I refuse to use any. the good answer is node.

When I insert require('assets/images/splashSignInAsset.png') function inside my Image component, I must check the node prop type, like the following:

Image.propTypes = {
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  source: PropTypes.node.isRequired
};

But I think the right answer is using React Native component prop type for the source:

import { Image as ImageNative } from 'react-native';
...
Image.propTypes = {
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  source: ImageNative.propTypes.source.isRequired
};

Update:

Also, the exact answer is using source prop type in the react-native source code, so the best answer is like following code:

source: PropTypes.oneOfType([
  PropTypes.shape({
    uri: PropTypes.string,
    headers: PropTypes.objectOf(PropTypes.string)
  }),
  PropTypes.number,
  PropTypes.arrayOf(
    PropTypes.shape({
      uri: PropTypes.string,
      width: PropTypes.number,
      height: PropTypes.number,
      headers: PropTypes.objectOf(PropTypes.string)
    })
  )
])