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?
CodePudding user response:
You need to extend AppProp and your custom attributes
import type { NextComponentType } from 'next' //Import Component type
//Add custom auth type with using union in type
type CustomAppProps = AppProps & {
Component: NextComponentType & {auth?: boolean}
}
function MyApp({ Component, pageProps: { session, ...pageProps } }: CustomAppProps) {
...
}
