如何扩展 NextPage 类型以将自定义字段添加到页面组件?

sch*_*gab 6 javascript typescript reactjs next.js

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

AdminDashboard.auth = {
  role: "admin",
  loading: <AdminLoadingSkeleton />,
  unauthorized: "/login-with-different-user", // redirect to this url
}
Run Code Online (Sandbox Code Playgroud)

使用 TypeScript 实现此目的的正确方法是什么?

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

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

type NextPageAuthProps = {
  Component: NextPageWithAuth,
  pageProps: any
}
Run Code Online (Sandbox Code Playgroud)

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

jul*_*ves 13

在页面中,您可以扩展内置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;
Run Code Online (Sandbox Code Playgroud)

然后,在 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) {
   //...
}
Run Code Online (Sandbox Code Playgroud)