GollyJer
GollyJer

Reputation: 26662

How do you extract a specific TypeScript prop type from a React component?

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?

Upvotes: 3

Views: 3448

Answers (1)

GollyJer
GollyJer

Reputation: 26662

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)

Upvotes: 5

Related Questions