NextImage's ImageProps is overriding src and alt properties

I've created a wrapper called IllustrationWrapper that I'm utilizing in different components.

import Image, { ImageProps } from 'next/image';

const getImageUrl = (illustrationName: string) => {
  return `https://my-link.com/illustrations/${illustrationName}.svg`;
};

interface IllustrationProps extends ImageProps {
  illustrationName: string;
}

const IllustrationWrapper = ({ illustrationName, ...props }: IllustrationProps) => {
  const imageUrl = getImageUrl(illustrationName);
  const altText = imageUrl.split(/(?=[A-Z])/).join(' ');

  return <Image {...props} src={imageUrl} alt={altText} unoptimized />;
};

export default IllustrationWrapper;

This wrapper is being used in the following component as an example:


import Link from 'next/link';
import IllustrationWrapper from '~/common/components/IllustrationWrapper';


const DesktopNav = () => (
    <div className="flex-shrink basis-[14.125rem]">
      <Link href="/" className="inline-block" aria-label="To main site">
        <IllustrationWrapper illustrationName="LogoLight" width={80} height={28} />
      </Link>
    </div>
)

export default DesktopNav;

However, when using it in DesktopNav, I encounter an error saying

Type '{ illustrationName: string; width: number; height: number; }' is missing the following properties from type 'IllustrationProps': src, alt

It seems like ImageProps from next is overriding my src and alt attributes in IllustrationWrapper. How can I resolve this?

Answer №1

You have created the IllustrationProps interface, which inherits all properties from ImageProps (such as alt and src) and adds a new property illustrationName,

To define this interface, you can use the following code:

interface IllustrationProps extends Omit<ImageProps, 'src' | 'alt'> {
  illustrationName: string;
}

This will exclude the specified properties.

TS playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I can't figure out why I'm getting the error message "Uncaught ReferenceError: process is not defined

I have a react/typescript app and prior to updating vite, my code checked whether the environment was development or production with the following logic: function getEnvironment(): "production" | "development" { if (process.env.NODE_E ...

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...

Error message: In the combination of NextJs and Redux, an issue has occurred where the program is unable to access properties of null, specifically in

I am just getting started with Next and redux, but I am facing an issue. The error shown above occurs when trying to select a redux value from the store. I have attempted using raw useSelector from redux toolkit, but it still results in the same error. ...

Having trouble importing .task files in a Next.js project with TypeScript?

I encountered an issue when trying to import a model.task file into my App.tsx file. After training a hand gesture recognition model in Python, I exported it to a model.task file. Now, I am attempting to import this file into my Next.js + Typescript proje ...

Encountered issue with accessing the Error Object in the Error Handling Middleware

Below is the custom error validation code that I have developed : .custom(async (username) => { const user = await UserModel.findOne({ username }) if (user) throw new ConflictError('username already used& ...

Is it possible to retrieve and utilize multiple Enum values in Typescript?

Combine enum values to retrieve corresponding enum strings. Consider the following scenario: enum EnumDays { NONE = 0, SUN = 1, MON = 2, TUE = 4, WED = 8, THU = 16, FRI = 32, SAT = 64, ALL = 127 } If I pass a value o ...

Update the source of an image dynamically in React / Next.js when it finishes

Is there a better way to implement a loader before the image source is fully loaded in React? I've attempted using the onLoad function, but it's not functioning correctly. I also tried using state, but encountered issues as the state changes aft ...

Error message reading: "Invalid `p.account.findUnique()` call while attempting to sign in with oauth in Next-auth

Within my Next.js application, I have integrated next-auth for authentication using @next-auth/prisma-adapter with MySQL as the chosen database provider. However, when attempting to sign in via OAuth, an error has been encountered: https://next-auth.js.org ...

Creating a Dynamic Example in Scenario Outline Using Typescript and Cypress-Cucumber-Preprocessor

I have a question that is closely related to the following topic: Behave: Writing a Scenario Outline with dynamic examples. The main difference is that I am not using Python for my Gherkin scenarios. Instead, I manage them with Cypress (utilizing the cypre ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

Retrieve the response type from a Prisma FindUnique query

Essentially, my goal is to determine the type of the result obtained from a FindUnique operation in Prisma. The current return type is any: import prisma from "@/libs/prismaDb"; import { Prisma } from "@prisma/client"; export default a ...

Issues with the ngModel data binding functionality

I'm currently working on the Tour of Heroes project and facing an issue with ngModel. It seems like hero.name is not being updated, or maybe it's just not reflecting in the view. Despite typing into the input field, the displayed name remains as ...

The useEffect function continues to fire twice even when the dependency array is empty

I found a helpful example at https://github.com/vercel/next.js/blob/canary/examples/with-firebase-authentication/utils/auth/useUser.js Although the effect is working fine and firing once, the functions inside are being called twice for some reason. us ...

Typescript's definition file includes imports that can result in errors

Occasionally, typescript may generate a definition file with code like the following, leading to compile errors: // issue.ts import { Observable } from 'rxjs'; class Issue { get data() { return new Observable(); } } // issue.d.ts class ...

Unable to access cloned repository on local server

After cloning the repository to experiment with it, I proceeded to run npm install and npm run dev as instructed. However, I encountered an error that left me scratching my head. Despite following the usage instructions which only mentioned running npm ins ...

What is the correct way to implement Vue.use() with TypeScript?

I am trying to incorporate the Vuetify plugin into my TypeScript project. The documentation (available at this link) suggests using Vue.use(), but in TypeScript, I encounter the following error: "error TS2345: Argument of type '{}' is not assign ...

The error message "TypeError: Attempting to access the 'map' property of an undefined value (React JS)" was displayed

I'm currently working on a recursive function that needs to iterate over an object type called ItemType. However, I encountered an error message: TypeError: Cannot read property 'map' of undefined This is the code snippet causing the issue: ...

Deploying AWS CDK in a CodePipeline and CodeBuild workflow

I am currently attempting to deploy an AWS CDK application on AWS CodePipeline using CodeBuild actions. While the build and deploy processes run smoothly locally (as expected), encountering an issue when running on CodeBuild where the cdk command fails w ...

Utilize nested object models as parameters in TypeScript requests

Trying to pass request parameters using model structure in typescript. It works fine for non-nested objects, but encountering issues with nested arrays as shown below: export class exampleModel{ products: [ { name: string, ...

Issue encountered while attempting to utilize a basic redux reducer to define a boolean value, regarding a mismatch in overrides

Currently, I am working on a project to enhance my understanding of Redux and Typescript. I am still navigating through the learning curve in this area. Based on what I have learned from a book, I have established a "slice" that includes definitions for r ...