Next.js + TypeScript 中使用 next-firebase-auth 时 Home 组件与 getServerSideProps 类型错误问题
解决Next.js + TypeScript + next-firebase-auth的类型不兼容问题
我来帮你搞定这个TypeScript类型报错,这是next-firebase-auth高阶组件常见的类型推断问题,咱们一步步来修复:
问题原因拆解
这个错误的核心是:withAuthUser高阶组件默认没有自动推断出你的Home组件需要的PageProps类型,它期望接收一个ComponentType<unknown>(也就是props类型未知的组件),但你的Home组件明确要求PageProps类型的props,两者类型不匹配才抛出了错误。
具体修复步骤
1. 给withAuthUser显式指定泛型参数
next-firebase-auth的withAuthUser支持泛型,我们可以直接传入PageProps,告诉它我们的组件需要的props类型:
export default withAuthUser<PageProps>({ whenUnauthedBeforeInit: AuthAction.SHOW_LOADER, whenUnauthedAfterInit: AuthAction.REDIRECT_TO_LOGIN, LoaderComponent: FullPageLoader, })(Home);
2. 修正getServerSideProps的AuthUser类型
别再用any来标注AuthUser了,直接用next-firebase-auth提供的AuthUser类型,既能获得类型提示,也能避免类型模糊:
首先导入对应类型:
import { AuthAction, useAuthUser, withAuthUser, withAuthUserTokenSSR, AuthUser } from "next-firebase-auth";
然后修改getServerSideProps的参数类型:
export const getServerSideProps = withAuthUserTokenSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN, })(async ({ AuthUser }: { AuthUser: AuthUser }) => { // ... 原有逻辑代码 })
3. (额外修正)修复请求URL拼写错误
我发现你代码里的请求URL写错了:htpp://应该是http://,这个错误会导致请求失败,记得一起修正。
修改后的完整代码
import { AuthAction, useAuthUser, withAuthUser, withAuthUserTokenSSR, AuthUser } from "next-firebase-auth"; import FullPageLoader from "../components/layout/FullPageLoader"; import SignUp from './signup/index'; import { useEffect } from 'react'; import { useRouter } from 'next/router'; import { NextPage } from "next"; type PageProps = { profile: boolean | { username: string, name: string, surname: string } } const Home: NextPage<PageProps> = (props) => { const AuthUser = useAuthUser() const router = useRouter() useEffect(() => { if (props.profile) { router.push(`/advisor/${AuthUser.id}/profile`) } }, [AuthUser.id, props.profile, router]) return ( <> <SignUp /> </> ); }; export const getServerSideProps = withAuthUserTokenSSR({ whenUnauthed: AuthAction.REDIRECT_TO_LOGIN, })(async ({ AuthUser }: { AuthUser: AuthUser }) => { const token = await AuthUser.getIdToken() // 修正URL拼写错误:htpp -> http const response = await fetch(`http://localhost:3001/profile/${AuthUser.id}/get-profile`, { method: 'GET', headers: { Authorization: token || '' } }) if (response.status !== 200) { const _props: PageProps = {profile: false} return { props: _props } } const profile = await response.json() const _props: PageProps = {profile} return { props: _props } }) // 显式传入泛型参数PageProps export default withAuthUser<PageProps>({ whenUnauthedBeforeInit: AuthAction.SHOW_LOADER, whenUnauthedAfterInit: AuthAction.REDIRECT_TO_LOGIN, LoaderComponent: FullPageLoader, })(Home);
内容的提问来源于stack exchange,提问作者Pere
相关产品推荐
相关产品推荐

