首页 > 解决方案 > 如何扩展 NextPage 类型以将自定义字段添加到页面组件?

问题描述

我正在尝试使用 TypeScript遵循下一个身份验证文档。使用以下代码和_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

标签: javascriptreactjstypescriptnext.js

解决方案


在页面中,您可以扩展内置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;

然后,在 custom_app中,您可以进行扩展AppProps,以便Componentprop 扩展您在页面中声明的类型。

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) {
   //...
}

推荐阅读