Using Next.js and TypeScript to Send Props to Dynamically Typed Objects

I am in the process of developing an application using Next.js with TypeScript. I have encountered an error message stating

Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties
when passing props to a component. How can I go about resolving this issue?

It is important to note that the object's type changes based on its category. The field details should be of type Details, while the subfield category_details within Details could either be of type Shirt or Bag, depending on the value of category_name.

{
    "data": {
        "id": 1,
        "details": [
            {
                "id": 1,
                "category_name": "shirt",
                "category_detail": {
                    "id": 1,
                    "size": "small",
                    "color": "white"
                }
            },
            {
                "id": 2,
                "category_name": "bag",
                "category_detail": {
                    "id": 13,
                    "width": 30,
                    "height": 15
                }
            },
            {
                "id": 3,
                "category_name": "shirt",
                "category_detail": {
                    "id": 45,
                    "size": "large",
                    "color": "pink"
                }
            }
        ]
    }
}
export interface Box {
  id: number;
  details: Details[];
}

export interface Details {
  id: number;
  category_name: string;
  category_detail: CategoryDetail[];
}

export interface Shirt {
  id: number;
  size: string;
  color: string;
}

export interface Bag {
  id: number;
  width: number;
  height: number;
}

export type CategoryDetail = Shirt | Bag;

The error occurs in the following section:

const Foo: NextPage = () => {
  const { box } = useFetchBox();

  return (
    <div>
      {box.details.map((detail) => (
        {detail.category_name === "shirt" && <ShirtDetail categroy_detail={detail.category_detail as unknown as typeof Shirt} />} // error: Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties from type 'ShirtDetail': id, size, color
        {detail.category_name === "bag" && <BagDetail categroy_detail={detail.category_detail as unknown as typeof Bag} />} // error: Type 'VoidFunctionComponent<BagDetailProps>' is missing the following properties from type 'BagDetail': id, width, height
      ))}
    </div>
  )
}

ShirtDetail is structured as follows:

interface ShirtDetailProps {
  category_detail: Shirt;
}

const ShirtDetail: React.VFC<ShirtDetailProps> = ({
  category_detail,
}) => {
  return (
    // some code
  );
};

export default ShirtDetail;

Prior to encountering this error, I attempted several steps:

  1. categroy_detail={detail.category_detail as Shirt}
    resulted in
    'Shirt' refers to a value, but is being used as a type here. Did you mean 'typeof Shirt'?
  2. Adjusted it to
    category_detail={detail.category_detail as typeof Shirt}
    as recommended, which prompted
    Conversion of type 'CategoryDetail[]' to type 'VFC<ShirtDetailProps>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  3. Modified it to
    category_detail={detail.category_detail as unknown as typeof Shirt}
    as suggested, resulting in
    Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties from type 'Shirt': id, size, color
  4. I am unsure how to proceed to resolve this issue.

Any assistance would be greatly appreciated.

Answer №1

I made an error by having the Shirt component defined in my project. TypeScript got confused between the Shirt type and the Shirt component. To resolve this issue, I renamed the Shirt component and the error vanished when using

categroy_detail={detail.category_detail as unknown as Shirt
.

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

Navigating the world of NestJs and TypeScript with the `mongoose-delete` plugin: a comprehensive guide

I am currently utilizing Mongoose within the NestJs library and I want to incorporate the mongoose-delete plugin into all of my schemas. However, I am unsure of how to implement it with nestJS and Typescript. After installing both the mongoose-delete and ...

Navigate to a different page in NextJs without causing a page refresh or altering the current state of the application

Recently, I encountered a challenge in my NextJS application while attempting to incorporate dynamic routes as endpoints on my server. Specifically, when accessing localhost:3000/register, the register.tsx file is loaded successfully. However, within one ...

Incorporating node packages into your typescript projects

I have been exploring various discussions on this forum but I am still unable to make it work. My goal is to compile the following code in TypeScript. The code is sourced from a single JavaScript file, however, due to issues with module inclusion, I am foc ...

Enhancing the NextPage Typescript Type: A Step-by-Step Guide

I'm working on a NextJS dashboard with role-based access control and I need to pass an auth object to each page from the default export. Here's an image showing an example of code for the Student Dashboard Home Page: Code Example of Student Dashb ...

The recognition of Angular ngrx union type actions is hindered by discrepancies in constructors

The actions classes and union type are displayed below. Unfortunately, these actions are not being recognized during the application's execution. export class Login implements Action { readonly type = LOGIN; constructor( public payload: { ...

Associate keys with strings and then map them to a specific type of strings in Typescript

I am endeavoring to develop a React component that extends the Octicons icon library available from Github at @githubprimer/octicons-react. One of the components exported by the library is the iconsByName type, which has the following structure: type ico ...

What are the steps to fixing the date time issue between NextJS and Firebase?

I am facing an issue with Firebase Database returning timestamps and unable to render them into components using Redux. How can I resolve this error and convert the timestamp to a date or vice versa? I need help with valid type conversion methods. import ...

Defining a state in Typescript and passing it as a prop

export interface ISideBarProps { open: boolean; setOpen: React.Dispatch<React.SetStateAction<boolean>>; } export default function SideBar({ open, setOpen }: ISideBarProps) { return ( <div className={`absolute left-0 top-0 h- ...

What causes the discrepancy in values displayed by enums in TypeScript when assigned integers in reverse order?

Recently diving into the world of TypeScript, I've been experimenting with different types in this language. One interesting data type I played with is enums. Here's an example of code I used: enum colors {red=1,green=0,blue,white}; console.lo ...

Navigating Through Angular Components

I have a layout with 3 components arranged like this: <app-header></app-header> <app-body></app-body> <app-footer></app-footer> However, I want to change the positioning of the footer and body as shown below: <app-he ...

What is the best method for exporting and importing types in React and Next.js apps?

Is there a way to export and import types from API responses in TypeScript? I have a type called Post that I want to re-use in my project. // pages/users.tsx type Post = { id: number; name: string; username: string; email: string; address: { ...

Is it possible to prevent the Virtual Keyboard from automatically appearing on mobile devices?

Whenever a user enters a number on a page component, the Virtual Keyboard on their Mobile device pops up and shifts the entire page. I am looking for a solution to either disable the on-screen keyboard or ensure that the text box remains visible even when ...

The combination of Tailwindcss and Nextjs is functioning perfectly except for components

It's really puzzling me. So, I've got this Navbar component that I'm importing into specific pages, and it's giving me some trouble. To keep things simple, for now, the Navbar component is just a styled div with a Link inside: /compone ...

Server-side rendering does not function properly on a Next.js production build

I have a Next.js app that I want to deploy to my own hosting. After running next export to build the app, I can successfully run it on my hosting server. However, I am facing an issue where the app does not perform server-side rendering (reloading any page ...

Methods for resolving a ViewStyle typescript issue in react native

Trying to pass a width parameter into StyleSheet is causing an error like this: <View style={styles.children(width)}>{children}</View> Here's how I'm trying to use it: const styles = StyleSheet.create({ modalContent: { flex: ...

A guide on passing variables to the MUI styled function within ReactJS

Is it possible to pass a variable directly to the styled function in order to conditionally change style properties while using MUI styled function? I want to achieve something like this: borderColor: darkMode ? 'white' : 'black' const ...

Is it advisable to use an if statement or question mark in TypeScript to prevent the possibility of a null value?

Currently delving into TypeScript and exploring new concepts. I encountered a scenario where inputRef.current could potentially be null, so I opted to directly use a question mark which seems to work fine. However, in the tutorial video I watched, they use ...

What is the syntax for implementing conditional statements within the style jsx of Next.js?

Recently, I've been exploring the use of <style jsx> in my Next.js project and encountered a scenario where I needed to style an element based on a conditional statement. Additionally, my project relies on tailwindCSS for styling: <div classN ...

Retrieving component attributes using jQuery or alternate event handlers

In my Angular2 component, I am facing an issue with using vis.js (or jQuery) click events. Despite successfully displaying my graph and catching click events, I encounter a problem where I lose access to my component's properties within the context of ...

Having trouble dispatching a TypeScript action in a class-based component

I recently switched to using this boilerplate for my react project with TypeScript. I'm facing difficulty in configuring the correct type of actions as it was easier when I was working with JavaScript. Now, being new to TypeScript, I am struggling to ...