How to Properly Pass Props with a Custom Type in Next.js Using TypeScript

preview_player
Показать описание
---

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Passing prop with custom type, nextJS, typescript

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---

The Problem

Imagine you have an array of JSON data fetched from an API, which you want to assign to a custom type. You define your custom data type like this:

[[See Video to Reveal this Text or Code Snippet]]

Next, you fetch this data using the getServerSideProps function, which looks something like this:

[[See Video to Reveal this Text or Code Snippet]]

However, once you pass the data prop to your component, you might run into an error message stating 'Property 'data' does not exist on type '{}'. This confusion arises because TypeScript cannot infer the type of the props, and as a result, it defaults to any, which is not ideal.

The Solution

To retain the strong typing of your props when passing data from getServerSideProps to your component, follow these steps:

Step 1: Specify the Component Prop Types

You need to explicitly define the type of the props your component will accept. In our case, the DigitalServices component needs to accept a prop of type Service. You can do this by modifying the component's declaration as follows:

[[See Video to Reveal this Text or Code Snippet]]

Step 2: Implement the Component

Once you have specified the prop types, you can implement the component using the fetched data. Here’s how you might structure your component:

[[See Video to Reveal this Text or Code Snippet]]

Step 3: Handle Optional Values

Since the properties in our Service type are marked as optional (e.g., id?, name?, description?), ensure that you handle these cases appropriately in your component to avoid runtime errors.

Conclusion

With this approach, you can confidently pass props without losing the benefits of type safety. Happy coding!
Рекомендации по теме
join shbcf.ru