Image type in typescript

Viewed 5304

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>
    );
};

3 Answers

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.

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>;
}

A file location is just a string, so the type of source would be string. For style, it depends. If it's an object you think is going to be re-used or extended, its better to create an interface and use that type. Try to take advantage of the typing system by avoiding general types such as object.

Related