javascript - 如何扩展 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
。
解决方案
在页面中,您可以扩展内置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
,以便Component
prop 扩展您在页面中声明的类型。
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) {
//...
}
推荐阅读
- python - Docker 上的 Gunicorn 在 Mac 上出现错误
- c# - Logical error in display/math not displaying initial result
- python - 在python中设计类似结构的c的最佳方法
- google-sheets - 如何对同一单元格内的单元格值进行排名
- python - 将字典写入输出文件时删除逗号
- json - 在 Go 中将字符串转换为 json
- python - 如何在 pandas datafrmae 中每 n 行展平
- python - 如何在python for循环中加载.txt文件?
- python - spaCy CLI 调试在由 spacy.gold.docs_to_json 转换的 CLI 格式 JSON 中显示 0 个训练/开发文档
- c# - 是否可以从 C# 组件覆盖 Form 的 CreateParams 方法/函数?