网站搜索

typescript - 关于将 getServerSideProps 类型传递给 Next.Js 页面 props,哪种做法在最佳实践中更好


我找到了两个都能正常工作的解决方案,但我不确定哪个方法更一致。

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
    };
};

第一种方法:

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

第二种方法:

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

答案#1

两者都可以,尤其是如果你只想让你的 props 有类型的话。

我更喜欢第一种方法,因为它还会对next注入的其他属性进行类型定义,例如req、res或pathname。它还会添加一个返回类型,而第二种方法则不会。