NextJS _app.tsx Component 和 pageProps 应该是什么 TypeScript 类型?

Cit*_*zen 20 javascript typescript reactjs next.js

这是 NextJS 的默认 _app.tsx:

function MyApp({ Component, pageProps }) {
  return (
    <Component {...pageProps} />
  )
}
Run Code Online (Sandbox Code Playgroud)

问题是,一旦你切换到 TypeScript,你就会在 ES6Lint 下收到一个警告,这些类型本质上被设置为类型 'any'。话虽如此,我无法弄清楚将这两个设置为哪种类型,以免以后不匹配的类型导致更多错误。我应该将这两个类型转换为哪些 TypeScript 类型?

kin*_*ser 39

您可以从nextjs.

import { AppProps } from 'next/app';

function MyApp({ Component, pageProps }: AppProps) {
  return <Component {...pageProps} />
}
Run Code Online (Sandbox Code Playgroud)

  • 这是推荐的方式,但这使得 pageProps 成为 any 类型,这不是很有用。在使用一种日期获取方法(例如“getInitialProps”)时,有什么方法可以应用泛型吗? (3认同)

Edi*_*ges 13

如果您仍然收到“函数缺少返回类型”的警告,只需添加返回类型 JSX.Element

import { AppProps } from 'next/app'

export default function MyApp({ Component, pageProps }: AppProps): JSX.Element {
  return <Component {...pageProps} />
}
Run Code Online (Sandbox Code Playgroud)


lpk*_*pke 7

NextJS 提供了AppProps一种您可以在_app组件中导入和使用的类型。但是,正如其他人所提到的,这种类型将子pageProps类型限制为“任何”。

我不是专家,所以如果我错了,请编辑它,但是通过对 NextJS 文件的一些快速挖掘,似乎虽然提供的AppProps类型通用的,但它接受的类型参数只会传递给<Component />. 它不像我们想要的那样被“初始”应用程序道具看到。我有一种可行的方法来覆盖它并告诉它使用你想要的 pageProps 任何东西。

请参阅下面的示例,了解我用来为App组件提供实际识别的自定义初始pageProps 类型的内容App。请注意,新的泛型类型将您的自定义 pageProps 类型传递给顶级pageProps变量以及NextJS 的AppProps泛型类型上的内置类型参数......真是一口!

_app.tsx

// importing the provided NextJS type
import type { AppProps as NextAppProps } from "next/app";

// modified version - allows for custom pageProps type, falling back to 'any'
type AppProps<P = any> = {
  pageProps: P;
} & Omit<NextAppProps<P>, "pageProps">;

// use the new type like so, replacing 'CustomPageProps' with whatever you want
export default function App({
  Component,
  pageProps,
}: AppProps<CustomPageProps>) {
  //...
}
Run Code Online (Sandbox Code Playgroud)