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?
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
};
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)
})
)
])
Currently is possible this statement as a type:
import { ImageProps } from 'react-native';
interface Props {
imageSource: ImageProps['source'];
}
Where ImageProps['source']
will return the correct type from the package and also receive further updates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With