如何使用 Typescript 在 Next.js 中的 _app.tsx 中的组件中添加新的 属性?
How can I add a new property to Component in _app.tsx in Next.js with Typescript?
我正在使用 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>
</>
);
}
我不是 Typescript 专家,所以我的问题是我如何 add/extend auth
属性 到带有 TS 的组件?
您需要扩展 AppProp
和您的自定义属性
import type { NextComponentType } from 'next' //Import Component type
//Add custom appProp type with using union in type
type CustomAppProps = AppProps & {
Component: NextComponentType & {auth?: boolean} // add auth type
}
function MyApp({ Component, pageProps: { session, ...pageProps } }: CustomAppProps) {
...
}
我正在使用 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>
</>
);
}
我不是 Typescript 专家,所以我的问题是我如何 add/extend auth
属性 到带有 TS 的组件?
您需要扩展 AppProp
和您的自定义属性
import type { NextComponentType } from 'next' //Import Component type
//Add custom appProp type with using union in type
type CustomAppProps = AppProps & {
Component: NextComponentType & {auth?: boolean} // add auth type
}
function MyApp({ Component, pageProps: { session, ...pageProps } }: CustomAppProps) {
...
}