【问题标题】:How can I add a new property to Component in _app.tsx in Next.js with Typescript?如何使用 Typescript 向 Next.js 中的 _app.tsx 中的组件添加新属性?
【发布时间】:2022-02-16 01:23:44
【问题描述】:

我正在使用 Next.js、NextAuth.js 和 Typescript 开发一些受保护的页面。我的_app.tsx 中的以下代码取自NextAuth.js 官方网站,但其中包含Component 不存在的属性auth,其类型为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 专家,所以我的问题是如何使用 TS 将 auth 属性添加/扩展到组件?

【问题讨论】:

    标签: reactjs typescript next.js next-auth


    【解决方案1】:

    您需要扩展 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) {
    ...
    }
    

    【讨论】:

    • 效果很好,谢谢!
    猜你喜欢
    • 2021-08-27
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2021-12-05
    • 2017-04-24
    • 2021-09-14
    • 2020-05-16
    相关资源
    最近更新 更多