【问题标题】:How to extend NextPage type to add custom field to page component?如何扩展 NextPage 类型以将自定义字段添加到页面组件?
【发布时间】:2021-11-14 18:10:16
【问题描述】:

我正在尝试使用 TypeScript 跟踪下一个身份验证 documentation。使用以下代码和文档中_app.tsx 中的一些代码,我可以保护页面:

AdminDashboard.auth = {
  role: "admin",
  loading: <AdminLoadingSkeleton />,
  unauthorized: "/login-with-different-user", // redirect to this url
}

使用 TypeScript 实现这一点的正确方法是什么?

我找到了一个可行的解决方案,但我不确定这是否是正确的方法:

export type NextPageWithAuth = NextPage & {
  auth: boolean,
  role: string
}

type NextPageAuthProps = {
  Component: NextPageWithAuth,
  pageProps: any
}

AppProps 类型比我自己的 NextPageAuthProps 复杂得多。

【问题讨论】:

    标签: javascript reactjs typescript next.js


    【解决方案1】:

    在页面中,您可以扩展内置的NextPage 类型以包含具有适当类型的auth 字段。

    import type { NextPage } from 'next';
    
    type PageAuth = {
      role: string
      loading: JSX.Element
      unauthorized: string
    };
    
    export type NextPageWithAuth<P = {}, IP = P> = NextPage<P, IP> & {
      auth: PageAuth
    };
    
    const AdminDashboard: NextPageWithAuth = () => {
      // Your `AdminDashboard` code here
    };
    
    AdminDashboard.auth = {
      role: "admin",
      loading: <AdminLoadingSkeleton />,
      unauthorized: "/login-with-different-user"
    };
    
    export default AdminDashboard;
    

    然后,在自定义 _app 中,您可以扩展 AppProps 以便 Component 属性扩展您在页面中声明的类型。

    import type { NextComponentType, NextPageContext } from 'next';
    import type { NextPageWithAuth } from '<path-to>/AdminDashboard';
    
    type NextComponentWithAuth = NextComponentType<NextPageContext, any, {}> & Partial<NextPageWithAuth>
    
    type ExtendedAppProps<P = {}> = AppProps<P> & {
      Component: NextComponentWithAuth
    };
    
    function MyApp({ Component, pageProps }: ExtendedAppProps) {
       //...
    }
    

    【讨论】:

    • 能否请您详细说明满足NextPageWithAuth类型的return语句。
    • @petrosmm 它扩展了现有的NextPage 类型,使其还包含auth 属性。
    • 这部分很清楚,但是,AdminDashboard 的示例返回行是什么样的?
    • @petrosmm 这就像任何其他 React 组件一样。额外的输入只允许在该组件上设置AdminDashboard.auth = { ... },而不需要 TypeScript 抱怨。
    • 哇,成功了,谢谢。那太简单了——仍然在这里学习。这似乎是我可能不熟悉的对象初始化器用法。点赞!
    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    • 2016-06-15
    相关资源
    最近更新 更多