3

I'm creating my own Image component and want to reuse React's image component ImageSourcePropType for my source/previewSource props.

Here's the component.

import React from 'react';
import { Image, ImageBackground } from 'react-native';

type ImageSourceProp = React.ComponentProps<typeof Image>.ImageSourcePropType; // HOW?

interface CachedImageProps {
  source: ImageSourceProp;
  previewSource: ImageSourceProp;
}

const CachedImage: React.FC<CachedImageProps> = ({ source, previewSource, ...remainingProps }) => {
  // console.log('TRIGGERED CachedImage')

  return (
    <ImageBackground source={previewSource|| source} fadeDuration={0} {...remainingProps}>
      <Image source={cachedSource} fadeDuration={0} {...remainingProps} />
    </ImageBackground>
  );
};

export default CachedImage;

How do I get the ImageSourcePropType?

2
  • Why not just import the type from 'react-native'? The type is exported from the module, so you can add it to your list of imports easily: import { Image, ImageBackground, ImageSourcePropType } from 'react-native'; Commented Jan 7, 2020 at 17:18
  • Ha! I didn't realize that. Also found another way after posting the question yesterday. I'll add an answer. Commented Jan 7, 2020 at 17:56

1 Answer 1

5

OK, figured this one out. There are two ways to do it.

  1. Access via name.

    type ImageSourcePropType = React.ComponentProps<typeof Image>['source'];
    
  2. Access via import.

    import { ImageSourcePropType } from 'react-native';
    

    (hat tip @kschaer)

Sign up to request clarification or add additional context in comments.

1 Comment

Yep! you can also roll your own type. type PropsOf<C> = C extends (props: infer P) => any ? P : never

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.