What are the best practices for passing the type of getServerSideProps to the page props in Next.js?

After discovering two working solutions, I am unsure which approach is more consistent.

interface ICatalogHome {
    response: Result<CatalogHomePageResponse>;
}
export const getServerSideProps: GetServerSideProps<ICatalogHome> = async (context) => {
    const appSlug = context.params?.appSlug;
    const { locale } = context;
    const response = await getCatalogHomePageData(appSlug as string, locale!);

    const notFound = !response;

    return {
        props: {
            response,
            ...(await serverSideTranslations(context.locale!, ['common', 'login']))
        }, // will be passed to the page component as props
        notFound
    };
};

One Approach:

const CatalogHome: NextPage<InferGetServerSidePropsType<typeof getServerSideProps>> = ({ response }) => {...}

Another Approach:

const CatalogHome = ({ response }: InferGetServerSidePropsType<typeof getServerSideProps>) => {...}

Answer №1

Either option works well, particularly if you are solely focused on typing your props.

I personally lean towards the initial method because it encompasses typing for other injected props like req, res, and pathname provided by next. Additionally, this approach includes a return type, unlike the second option.

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

Understanding the attribute types in Typescript React

While working on code using Typescript + React, I encountered an error. Whenever I try to set type/value in the attribute of <a> tag, I receive a compile error. <a value='Hello' type='button'>Search</a> This piece o ...

Tips for creating a script that waits for a specific amount of time before moving on to the next execution block in Protractor

Need to automate a test case that involves filling out a form with 5 date pickers and 30 fields. Once the form is filled, a jar needs to be invoked to retrieve the data from the DB and process it independently. Note: The jar does not send any value back t ...

Error encounter when loading the chunk for FusionCharts's overlappedbar2d.js in React.js: fusioncharts.overlapped

Currently, I am working on a web application that utilizes next.js and FusionCharts. Within the app, various FusionChart types have already been set up. My task now is to integrate the Overlapping Bars chart as outlined in the following documentation: How ...

Is it feasible to programmatically define the onClick action for an element within a ReactNode?

Let's discuss a function called addAlert that adds messages to an array for display as React Bootstrap alerts. While most alerts are simple text, there's one that comes with an "undo the last action" link. The challenge is that when this "undo" l ...

Can Typescript restrict a value to only exist within a specified set of key names within the same object?

I am completely new to Typescript and I am fascinated by the way it can check types. One thing I would like to know is if Typescript can be used to verify at compile time whether a value's domain falls within a predefined set of key names that are de ...

Error: No default Firebase App named '[DEFAULT]' exists. Please remember to call Firebase App.initializeApp() to create the app (app/no-app). This issue is located at the app

Currently, I am in the process of learning how to integrate Firebase Functions into an Ionic + Angular project. My goal is to develop a custom function that retrieves all games from a collection and returns an array sorted by the "count" attribute. Initia ...

Looping through children components in a LitElement template

I aim to generate <slot>s for each child element. For instance, I have a menu and I intend to place each child inside a <div> with a item class. To achieve this, I have devised a small utility function for mapping the children: export functio ...

Angular 6 component experiencing issues with animation functionality

I've implemented a Notification feature using a Notification component that displays notifications at the top of the screen. The goal is to make these notifications fade in and out smoothly. In my NotificationService, there's an array that holds ...

What could be the reason for the next.js Script tag not loading the third-party script when using the beforeInteractive strategy?

I have been trying to understand how the next.js Script tag with the beforeInteractive strategy works. I am currently testing it with lodash, but I keep encountering a ReferenceError: _ is not defined. I was under the impression that when a script is loade ...

Error: The reference to the window object cannot be found, occurring when attempting to synchronize the search input state with react instant search

Currently, I am working with Next.js and facing a challenge regarding syncing my search state with URL query parameters. The goal is to maintain the search input state during navigation without losing it. Although Next.js is a server-side language, I am l ...

Creating an Angular library that utilizes HTML components from the application

This is my first attempt at developing an angular library. My goal is to create a header and footer library for angular. The challenge lies in making sure that it integrates seamlessly with the HTML structure of the application it is being used in. Below ...

Unlock the Power of Angular with Custom Decorators: Accessing ElementRef Made Easy

I am currently working on implementing a decorator for Host CSS Variable Binding in Angular5. However, I am facing difficulties in properly implementing it with the given code. Is there a way to define ElementRef from within the decorator itself? export f ...

Tips for querying enum data type using GraphQL

I am having trouble querying an enum from GraphQL in my Nest.js with GraphQL project. I keep getting an error message saying: "Enum 'TraitReportType' cannot represent value: 'EMBEDDED'". I have tried using type:EMBEEDED, but it did not ...

Issue with React Hot Toast not displaying properly due to being positioned behind the <dialog>

The Challenge of Toast Notifications Visibility with <dialog> Element tl;dr When utilizing the native dialog.showModal() function, the <dialog> element appears to consistently remain on top, which causes toast notifications to be obscured by ...

Dealing with React and Firebase Authentication Errors: How to Handle Errors for Existing Accounts with Different Credentials

According to the documentation at https://firebase.google.com/docs/auth/web/google-signin#expandable-1, when error.code === 'auth/account-exists-with-different-credential', signInWithPopup() should return an error.email. However, in my specific c ...

Unlocking Not Exported Type Definitions in TypeScript

Take a look at this TypeScript code snippet: lib.ts interface Person { name: string; age: number; } export default class PersonFactory { getPerson(): Person { return { name: "Alice", age: 30, } } } ...

What is the best way to structure this React state container for modularity?

At my workplace, we have developed a state container hook for our React application and related packages. Before discussing what I'd like to achieve with this hook, let me provide some background information. Here is the functional code that's co ...

I'd like some clarification on the code that dynamically adds routes using Typescript and Node Express. Can someone please

Running my API server with node/typescript and express / express validator, I came across this code that I found really useful for separating route logic: function createCustomRouter(route: Array<CustomRouteEntry>): Router { const customRouter = R ...

esBuild failing to generate typescript declaration files while running in watch mode

Recently dove into using edBuild and I have to say, it's been a breeze to get up and running - simple, fast, and easy. When I execute my esBuild build command WITHOUT WATCH, I can see that the type files (.d.ts) are successfully generated. However, ...

Using TypeScript to utilize an enum that has been declared in a separate file

Imagine I have defined an enum in one file (test1.ts): export enum Colors{ red=1, blue=2, green=3 } Then in another file (test2.ts), I am creating a class with a method. One of the parameters for that method is a Color from the Colors enum: ...