Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image type in typescript

Hello guys what should be the type of Source and Style

The source is going to contain the image file location. Something like this

source = require('../../../assets/user.png')

and style is going to have an Object of styles but not sure if I write style: Object will be right.

export interface AvatarProps {
    source?: any;  <<<<< Don't want to use any
    style?: any;   <<<<< Don't want to use any
    shape?: string;
    ImageComponent?: React.ComponentType;
    size?: 'tiny' | 'small' | 'medium' | 'large' | 'giant';
}

export const Avatar: FunctionComponent<AvatarProps> = ({
    shape,
    style,
    size = 'medium',
    ImageComponent,
    source = require('../../../assets/user.png'),
}) => {
    return (
        <View>
         ....
        </View>
    );
};

like image 727
amy Avatar asked May 14 '26 22:05

amy


2 Answers

You can use ImageSourcePropType and ImageStyle from react-native.

interface AvatarProps {
  style: StyleProp<ImageStyle>;
  source: ImageSourcePropType;
} 

For source, ImageSourcePropType will cover remote and local images

<MyAvatar source={{ uri: 'https://placehold.it/50x50' }} />
<MyAvatar source={require('../assets/hello-world.png} />

A tip: If you go into the React Native documentation, it may tell you the types. https://reactnative.dev/docs/image#source mentions type ImageSourcePropType

For style, https://reactnative.dev/docs/image#style it doesn't explicitly mention the type, however, if you are using VSCode and you hover over a prop, it'll reveal its desired type. A screenshot of a User hovering over a prop and the type being revealed in VSCode

If hovering doesn't work, command (⌘) and click the prop, and it'll show you the desired type.

export interface ImageProps extends ImagePropsBase {
    /**
     *
     * Style
     */
    style?: StyleProp<ImageStyle>;
}
like image 161
Dan Avatar answered May 16 '26 11:05

Dan


source is just a string. Importing binary data is not necessary; often all we need is a URL。

For style, since you are using React, you can use React.CSSProperties to be its type.

like image 33
vipcxj Avatar answered May 16 '26 12:05

vipcxj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!