How to properly use GetServerSidePropsResult in NextJS?

Viewed 21

I have the following component in a NextJS project:

import { GetServerSideProps, GetServerSidePropsResult } from "next";

export const getServerSideProps: GetServerSideProps = async () => {
    return { props: { data: "asdf" } };
};

const Home = (props: GetServerSidePropsResult<{ data: string }>["props"]) => (
    <div>My data is {data}</div>
);

export default Home;

This works exactly as expected in the browser. However, I get an intellisense error on the props type:

Property 'props' does not exist on type 'GetServerSidePropsResult<{ data: string; }>'.

That's pretty clearly not true if we look at the definition for GetServerSidePropsResult:

(alias) type GetServerSidePropsResult<P> = {
    props: P | Promise<P>;
} | {
    redirect: Redirect;
} | {
    notFound: true;
}

All this trouble is telling me that I'm doing something wrong, but it seems like there should be a way to use this type in a DRY way. If I have to provide { data: string } anyway, then I might as well just do this:

const Home = ({ data }: { data: string }) => <div>My data is {data}</div>;

Which works, but obviously doesn't use the included GetServerSidePropsResult type. Am I meant to just not interface with that?

I'm also aware of InferGetServerSidePropsType, which works fine like this:

const Home = ({
    data,
}: InferGetServerSidePropsType<typeof getServerSideProps>) => (
    <div>My data is {data}</div>
);

Or even this (though it's annoyingly missing the hinting on props.data even though it doesn't show an error, but with hinting would likely be the most useful of all the options):

const Home = (
    props: InferGetServerSidePropsType<typeof getServerSideProps>
) => <div>My data is {props.data}</div>;

But I'm left unsure as to which is more "correct" of these.

0 Answers
Related