Error encountered in Typescript: The property 'prevUrl' is expected to be present in the props object, but it appears to be missing

When trying to access the props.prevUrl property, the following error is encountered: Property 'prevUrl' does not exist on type '{ nextUrl: string; } | { prevUrl: string; nextUrl: string; } | { prevUrl: string; confirm: () => void; }'. How can this be resolved?

function NavigationButtons({
  variant,
  ...props
}:
  | {
      variant: 'first';
      nextUrl: string;
    }
  | { variant: 'middle'; prevUrl: string; nextUrl: string }
  | { variant: 'last'; prevUrl: string; confirm: () => void }) {
  return (
    <nav
      className={`fixed bottom-0 left-0 right-0 flex bg-neutral-white p-4 ${
        variant === 'first' && 'justify-end'
      } lg:static lg:mt-auto`}
    >
      {(variant === 'middle' || variant === 'last') && (
        <Link href={props.prevUrl}>
          <button>Go Back</button>
        </Link>
      )}
      {(variant === 'first' || variant === 'middle') && (
        <button className='rounded bg-primary-marine-blue px-4 py-2 text-neutral-alabaster'>
          Next Step
        </button>
      )}
      {variant === 'last' && <button>Confirm</button>}
    </nav>
  );
}

View image here

Answer №1

By destructing the props at the beginning, you are isolating variant from the rest of the props, creating independence that prevents the compiler from narrowing down the props based on the value of variant. One way to avoid this issue is by not using destructuring, as shown below:

function NavigationButtons(props:
  | {
      variant: 'first';
      nextUrl: string;
    }
  | { variant: 'middle'; prevUrl: string; nextUrl: string }
  | { variant: 'last'; prevUrl: string; confirm: () => void }) {
  return (
    <div>
       {(props.variant === 'middle' || props.variant === 'last') && <a href={props.prevUrl} /> }
    </div>
  )
}

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 am developing a JWT authentication and authorization service for my Angular application. However, I am running into issues when trying to implement observables

I have created a user class and required interfaces as outlined below: user.ts import { Role } from '../auth/auth.enum' export interface IUser { _id: string email: string name: IName picture: string role: Role | string userStatus: b ...

Guide for releasing a typescript package compatible with both node and react applications

I have developed an authentication library in TypeScript which I have released on npm. My goal is to make this library compatible for use in both Node.js projects and React projects created with create-react-app. However, I am facing an issue where one of ...

Looking to make an API call with every keystroke in a React application, however, the response may contain a large number of objects

Currently, I am utilizing react and axios for the frontend while relying on nextjs with prisma for the backend. Within my database, there are 4000 exercises related to fitness stored as data. My objective is to create a function where each keystroke trigge ...

I make a commitment to continue working until the issue is resolved and the page is successfully changed in the Protractor

I have a table with rows and I need to click on the edit button in a row that has a specific label (test server label). This is my function: public selectOnRow( textSelector:string , clickableSelector : string , value:string) { let promise = new Prom ...

Get a List exported as an Excel file using Spring Boot and Nextjs

I am attempting to implement a feature in my Nextjs frontend where users can download a list as an Excel file by clicking on a button. The backend of my application is built using Spring Boot, and I need to send the file from there so that users can downlo ...

Encountering a message error for the Collapse component in Material UI

I'm currently working on creating a hamburger menu using Material UI List in Next.js, inspired by the Nested List example in the Material UI documentation. However, I've encountered an error when using "collapse" in my code. The rest of the code ...

The error message "Unable to find 'encoding'" in NextJS is triggered by the use of try/require in the node_modules folder

Running a NextJS app in typescript with version 13.4.19, utilizing @apollo/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7e687f7b687f4d392334233e">[email protected]</a> triggers a warning during the build proce ...

Utilizing Angular 4 Typescript to create cascading drop-downs within a table

As a newcomer to Angular, I am in the process of building my first application using Angular 4 and TypeScript. I would like to implement Cascading dropdowns within a table using Angular 4. Currently, I am facing an issue where changing the dropdown selec ...

What data structure is used to store HTML elements in TypeScript?

Currently, I am dealing with a typescript variable that holds the outcome of a query on the DOM: let games = document.getElementsByTagname("game"); My uncertainty lies in identifying the appropriate type for the resulting array. Should I expect an array ...

Traversing fields of a document within a Firestore collection using Angular

Attempts to retrieve the user's photoUrl based on their ID have been unsuccessful. Here is a snapshot of my firestore collection, can someone please guide me on how to access the photoUrl? https://i.stack.imgur.com/p2Zvm.jpg The main collection is &ap ...

Navigating collisions in the ECS architecture: Best practices

I'm currently developing a game using typescript and the ECS design pattern. One of the challenges I'm facing is handling collisions between different entities within the game world. I have an entity called Player which comprises several componen ...

Mastering the art of connecting content within Prismic

I have been working on creating a mega menu for my website header, but I am encountering a type error. Has anyone else faced this issue before and how did you resolve it? I am currently importing the generated types from @/prismicio-types. Here is an exam ...

Implementing a Navigation Drawer with Next.js and React

I'm looking to implement React Navigation v5 (Drawer navigation) with Next.js and I have a query about how they can be integrated seamlessly. Basically, the React Navigation (Drawer navigation) relies on the React Navigation Screens component to ...

Issue encountered while conducting tests with Jest and React Testing Library on a React component containing an SVG: the type is not recognized in React.jsx

In my Next.js 12.1.4 project, I am using Typescript, React Testing Library, and SVGR for importing icons like this: import ChevronLeftIcon from './chevron-left.svg' The issue arises when running a test on a component that includes an SVG import, ...

What is the best way to prevent event propagation in d3 with TypeScript?

When working with JavaScript, I often use the following code to prevent event propagation when dragging something. var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on('dragstart', function(e) { d3.event.sourceEvent ...

Error: In Angular and Typescript, the function this.$resource is not recognized

I keep encountering a TypeError: this.$resource is not a function. Below is the code snippet causing the issue: export class DataAccessService implements IDataAccessService { static $inject = ["$resource"]; constructor(private $resource: ng ...

Ways to dynamically update button properties in Angular 2

Customized Template, <div *ngFor="let item of items" class = "col-sm-12 nopadding"> <a class="button buttonaquacss button-mini button-aqua text-right pull-right" [ngClass]="{activec: isActive}" (click)='updateStatus(item)& ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Issue with incorrect inference of TextField `helperText` when using Formik with Material-UI

Upgrading to react-scripts 5 has caused an issue with the helperText on the TextField component. My TypeScript knowledge is not strong, so I'm having trouble fixing it. Here's more information about the problem: The error message: TS2322: Type & ...

Avoiding the insertion of duplicates in Angular 2 with Observables

My current issue involves a growing array each time I submit a post. It seems like the problem lies within the second observable where the user object gets updated with a new timestamp after each post submission. I have attempted to prevent duplicate entr ...