如何使用 Typescript 将新属性添加到 Next.js 中 _app.tsx 中的组件?

Ale*_*iva 13 typescript reactjs next.js next-auth

我正在使用 Next.js、NextAuth.js 和 Typescript 开发一些受保护的页面。我的以下代码_app.tsx取自 NextAuth.js 官方网站,但其中包含一个auth不存在Component的类型为 的属性var Component: NextComponentType<NextPageContext, any, {}>,因此 TS 显示了一个错误:

function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
  return (
    <>
      <SessionProvider session={session}>
        {Component.auth ? (
          <Auth>
            <Component {...pageProps} />
          </Auth>
        ) : (
          <Component {...pageProps} />
        )}
      </SessionProvider>
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

我不是 Typescript 专家,所以我的问题是如何auth使用 TS 添加/扩展该属性到组件?

Che*_*del 26

您需要扩展AppProp并添加自定义属性

import type { NextComponentType  } from 'next' //Import Component type

//Add custom appProp type then use union to add it
type CustomAppProps = AppProps & {
  Component: NextComponentType & {auth?: boolean} // add auth type
}

function MyApp({ Component, pageProps: { session, ...pageProps } }: CustomAppProps) {
...
}
Run Code Online (Sandbox Code Playgroud)