0

I have what is essentially some boilerplate code from the next/auth docs in my _app.tsx file

type CustomAppProps = AppProps & {
  Component: NextComponentType & { auth?: boolean }
  pageProps: {
    session: Session
  }
}

function MyApp({
  Component,
  pageProps: { session, ...pageProps },
}: CustomAppProps) {
  return (
    <SessionProvider session={session}>
      <ChakraProvider theme={theme}>
        {Component.auth ? (
          <Auth>
            <Component {...pageProps} />
          </Auth>
        ) : (
          <Component {...pageProps} />
        )}
      </ChakraProvider>
    </SessionProvider>
  )
}

function Auth({ children }: { children: ReactElement<any, any> }) {
  const router = useRouter()
  const { status } = useSession({
    required: true,
    onUnauthenticated() {
      router.push(PATHS.LOGIN)
    },
  })

  if (status === 'loading') {
    return <Loader />
  }

  return children
}

export default MyApp

However, when using the .auth boolean property on a component I receive a TS error Property "auth" does on exist on type 'FC<{}>'

export const HomePage:React.FC = () => {
  const { user, isLoading } = useGetUserDetails()
  if (isLoading || !user) return <Loader />

  return (
    <Box>
      <Text fontSize="2rem" as="p" textStyle="p">
        Welcome: {user.email}
      </Text>
      <Button onClick={() => signOut()}>Sign Out</Button>
    </Box>
  )
}

HomePage.auth = true // Property "auth" does on exist on type 'FC<{}>'

the functionality is as expected but the error is annoying. next/auth does not provide docs for application of this in Typepscript from what I can see. Does anyone know of a solution?

juliomalves
  • 42,130
  • 20
  • 150
  • 146
Ben_Sven_Ten
  • 529
  • 3
  • 21
  • 1
    Well, from a TS perspective, you can set the return type `HomePage` to `React.FC & { auth: boolean; }`. Not sure if that is what you are looking for. – John Paul R Oct 08 '22 at 20:52
  • 1
    @JohnPaulR yes thats exactly it. Missed that one. Thanks! – Ben_Sven_Ten Oct 08 '22 at 20:52
  • @JohnPaulR Curious, but wouldn't `React.FC<{ auth: boolean }>` work? – Joel Oct 08 '22 at 21:04
  • 2
    @Joel An interesting question! Actually, it wouldn't. The generic `React.FC` accepts a type `T` that lets you define the props (`T`) that the function component accepts (these are the parameters of the function). When we define `HomePage` as `React.FC & { auth: boolean; }`, we're saying: "this value is a function component, but _also_ has aa `auth` property." instead of "value is a function component, which accepts an auth parameter". Lmk if that clarifies. – John Paul R Oct 08 '22 at 21:23

0 Answers0