You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS中如何正确使用GetServerSidePropsResult类型?

Next.js中GetServerSideProps的正确类型使用方式

问题描述

我在NextJS项目中有如下组件:

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;

组件运行正常,但props类型出现智能提示错误:

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

查看GetServerSidePropsResult的定义:

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

我希望以DRY的方式使用类型,不想手动定义{ data: string }。尝试了InferGetServerSidePropsType的两种写法都可行,但不确定哪种更正确:

写法1(解构):

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

写法2(非解构):

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

问题分析

为什么直接用GetServerSidePropsResult<{ data: string }>["props"]会报错?

GetServerSidePropsResult是联合类型,包含三个分支:正常返回props、重定向、返回404。TypeScript对联合类型的属性访问有严格限制:只有当所有分支都包含该属性时,才能直接访问。而redirect和notFound分支没有props属性,所以TS会报错,提示无法确定当前类型是否包含props。

为什么不应该直接使用GetServerSidePropsResult?

GetServerSidePropsResult是getServerSideProps的返回类型,涵盖了所有可能的返回情况,但组件实际接收的props只会是正常返回props分支的类型。直接使用这个联合类型的props分支,本质上是忽略了其他分支的可能性,不符合TypeScript的类型安全原则,也会导致类型报错。

正确解决方案:使用InferGetServerSidePropsType

Next.js专门提供了InferGetServerSidePropsType这个工具类型,它会自动分析getServerSideProps的返回值,提取出组件实际接收的props类型,无需手动重复定义,完美符合DRY原则。

两种写法的对比

  • 解构写法:是React组件的常规写法,直接解构props中的字段使用,代码更简洁,同时TypeScript的智能提示完全正常,是推荐的写法。
  • 非解构写法:本身也是正确的类型用法,如果出现props.data无智能提示的情况,大概率是TS配置或编辑器缓存问题,修复后同样能正常工作。但解构写法更符合React开发的习惯,代码可读性更高。

总结

优先选择解构写法,既符合DRY原则,又保证类型安全和代码简洁性。

内容的提问来源于stack exchange,提问作者Christian Legge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 08:01:41