[英]How to Correctly Type Next.js getServerSideProps as a Function Declaration
I'm working with typing getServerSideProps
( guide docs , API reference docs ) but all of the documentation that I can find relates to declaring it as a function expression.我正在使用
getServerSideProps
( 指南文档, API 参考文档),但我能找到的所有文档都与将其声明为 function 表达式有关。 I'm looking to code it as a function declaration but can't find any documentation on it and am having trouble getting it to work.我希望将其编码为 function 声明,但找不到任何关于它的文档并且无法使其正常工作。
As a function expression (this works):作为 function 表达式(有效):
import { GetServerSideProps } from 'next';
export type Data = {
example: string,
};
export const getServerSideProps: GetServerSideProps<data: Data> = async (context) => {
const data: Data = { example: '' };
...
return {
props: data
};
}
This is where I'm at with it as a function declaration:这就是我将其作为 function 声明的地方:
import { GetServerSideProps, GetServerSidePropsContext } from 'next';
export type Data = {
example: string,
};
export async function getServerSideProps(context: GetServerSidePropsContext): Promise<GetServerSideProps<data: Data>> {
const data: Data = { example: '' };
...
return {
props: data
};
}
TypeScript is happy with this as far as the declaration itself goes, but I get an error on the component declaration TS2339: Property 'example' does not exist on type 'never'.
就声明本身而言,TypeScript 对此感到满意,但我在组件声明
TS2339: Property 'example' does not exist on type 'never'.
export default function ExampleComponent(data: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<>
<p>{data.example}</p>
</>
);
}
What am I missing?我错过了什么? How can I properly use a function declaration for
getServerSideProps
and get the typing right?如何正确使用 function 声明
getServerSideProps
并正确输入?
Thanks.谢谢。
This works but see my other answer which makes better use of the types provided by Next.js.这行得通,但请参阅我的其他答案,它更好地利用了 Next.js 提供的类型。
Looks like I found an answer to this myself but if this can be done better then I'd appreciate hearing about it.看起来我自己找到了答案,但如果可以做得更好,那么我会很高兴听到它。
import { GetServerSidePropsContext } from 'next';
export async function getServerSideProps(context: GetServerSidePropsContext): Promise<{props: Data}> {
const data: Data = { example: '' };
...
return {
props: data
}
}
Ok pretty sure I found the correct answer to this now, having discovered the GetServerSidePropsResult
type from next
.好的,很确定我现在找到了正确的答案,从
next
发现了GetServerSidePropsResult
类型。
import { GetServerSidePropsContext, GetServerSidePropsResult } from 'next';
export async function getServerSideProps(context: GetServerSidePropsContext): Promise<GetServerSidePropsResult<Data>> {
const data: Data = { example: '' };
...
return {
props: data
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.