在 TypeScript 的 Next.js 中創(chuàng)建 HOC withAuth 的最佳方法是什么?
問題:
我有一個(gè) Next.js 應(yīng)用程序,并且正在使用next-authpackage.json。我正在嘗試創(chuàng)建一個(gè) HOC 來包裹實(shí)際組件并確定它是否有會(huì)話。我也在使用 eslint。這是我的代碼:
import { useRouter } from 'next/navigation'; import { useSession } from 'next-auth/react'; type Props = any; const withAuth = (Component: React.ComponentType<Props>) => { const Auth = (props: Props) => { const router = useRouter(); const { status } = useSession({ required: true, onUnauthenticated() { router.push('/welcome/login'); }, }); if (status === 'loading') { return 'Loading ...'; } return <Component {...props} />; }; return Auth; }; export default withAuth;
Eslint 向我發(fā)出有關(guān)我使用 type 的警告any
。我嘗試將這兩行更改為使用通用類型的位置:
const withAuth = <P extends {}>(Component: React.ComponentType<P>) => { const Auth = (props: P) => {
但現(xiàn)在它報(bào)錯(cuò)了:
Error: Don't use `{}` as a type. `{}` actually means "any non-nullish value". - If you want a type meaning "any object", you probably want `object` instead. - If you want a type meaning "any value", you probably want `unknown` instead. - If you want a type meaning "empty object", you probably want `Record<string, never>` instead. - If you really want a type meaning "any non-nullish value", you probably want `NonNullable<unknown>` instead. @typescript-eslint/ban-types
當(dāng)我們必須將組件作為 props 傳遞時(shí),編寫 HOC 的最佳方法是什么?我不知道它會(huì)是什么樣的組件
解決方案或解答
一般來說,TypeScript 建議不要使用{}作為泛型類型約束,因?yàn)樗粫?huì)施加任何類型檢查約束,因此它本質(zhì)上與使用 一樣寬松any。
您可以使用unknownorRecord<string, unknown>來獲得更好的類型安全性,并且 ESLint 錯(cuò)誤也不會(huì)彈出。
這些類型基本上假設(shè)您不知道該對(duì)象將采用什么形狀,但它不會(huì)是nullor undefined,使其足夠靈活以包裝任何組件。
所以在你的情況下:文章來源:http://www.zghlxwxcb.cn/article/381.html
const withAuth = <P extends Record<string, unknown>>( Component: React.ComponentType<P> ): React.FC<P> => { const Auth: React.FC<P> = (props) => { const router = useRouter(); const { status } = useSession({ required: true, onUnauthenticated() { router.push('/welcome/login'); }, }); if (status === 'loading') { return 'Loading ...'; } return <Component {...props} />; }; return Auth; }; export default withAuth;
所以在這里, props 參數(shù)的類型不是 ,any而是 類型P,這是我們限制為 的泛型類型Record<string, unknown>。文章來源地址http://www.zghlxwxcb.cn/article/381.html
到此這篇關(guān)于在 TypeScript 的 Next.js 中創(chuàng)建 HOC withAuth 的最佳方法是什么?的文章就介紹到這了,更多相關(guān)內(nèi)容可以在右上角搜索或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!