如何在 Typescript 中定义 Next js 上下文类型?

Sam*_*mmi 4 typescript next.js

我需要知道如何定义下一个 jsContext类型及其req类型?

这里我写了这个getServerSideProps函数——

//Server side functions
export const getServerSideProps: GetServerSideProps = async (context) => {
    await getMovies(context, context.req);
    return { props: {} }
}
Run Code Online (Sandbox Code Playgroud)

我在这里写了这个函数 -

export const getMovies = (context: **types, req: **types) => {
    //here the main function
}
Run Code Online (Sandbox Code Playgroud)

这里如何定义context类型和req类型?

请帮我?

MHe*_*bes 7

在 VS Code 中,您可以右键单击某个类型,然后单击“转到定义”。的类型GetServerSideProps在 next.js 中定义为:

export type GetServerSideProps<
  P extends { [key: string]: any } = { [key: string]: any },
  Q extends ParsedUrlQuery = ParsedUrlQuery,
  D extends PreviewData = PreviewData
> = (
  context: GetServerSidePropsContext<Q, D>
) => Promise<GetServerSidePropsResult<P>>
Run Code Online (Sandbox Code Playgroud)

所以看起来context参数是 a GetServerSidePropsContext,带有一些通用参数。

这意味着你的函数变成:

import type {
  GetServerSideProps,
  GetServerSidePropsContext,
  PreviewData,
} from "next";
import { ParsedUrlQuery } from "querystring";

// ...

export function getMovies<Q extends ParsedUrlQuery, D extends PreviewData>(
  context: GetServerSidePropsContext<Q, D>,
  req: GetServerSidePropsContext<Q, D>["req"]
) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)

不过,我只是删除req参数,它已经在context. getMovies如果需要的话,将其提取到里面。