javascriptreactjsvite

TypeError: Type {} is not assignable to type string | undefined when importing an image in React


I'm using an image in my React component, and although it displays correctly, I keep seeing this warning:

TypeError: Type {} is not assignable to type string | undefined

Here’s my code:

import profilePic from './assets/profile.jpeg';

function Card() {
    return (
        <div className="card">
            <img src={profilePic} alt="profile picture" />
            <h2>Profile Card</h2>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui, reiciendis.</p>
        </div>
    );
}

export default Card;

I'm using JavaScript in a React project, and profile.jpeg is located in the assets folder.

I also tried using require instead of import:

const profilePic = require('./assets/profile.jpeg');

But it didn’t resolve the warning. Any suggestions on correctly managing this image import to avoid the warning?


Solution

  • There are two ways to fix this. Check the solutions below:

    1. Type assertion with as keyword.

      <img src={profilePic as string} alt="profile picture" />
      

    1. Create a type declaration file.

    In src folder, create a file with a name ending with .d.ts. For example file name images.d.ts and write the declaration as below:

    // src/images.d.ts
    declare module '*.jpeg' {
        const value: string;
        export default value;
    }
    

    This solution will work for all the jpeg file imports.