I'm developing some protected pages using Next.js, NextAuth.js and Typescript. The following code from my _app.tsx
was taken from the NextAuth.js official website but that includes a property auth
that does not exist for Component
which has the type var Component: NextComponentType<NextPageContext, any, {}>
, so TS is displaying an error for that:
function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
return (
<>
<SessionProvider session={session}>
{Component.auth ? (
<Auth>
<Component {...pageProps} />
</Auth>
) : (
<Component {...pageProps} />
)}
</SessionProvider>
</>
);
}
I'm not a Typescript expert, so my question is how can I add/extend that auth
property to the Component with TS?
You need to extend AppProp
and add your custom attributes
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) {
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.