【发布时间】:2022-10-24 00:24:34
【问题描述】:
我在 Next.js 中为 getServerSideProps 创建了一个身份验证包装器。尽管在钩子中以及在需要它的页面上,但我遇到了一些类型错误。这是包装器代码,后面是 TS 错误。请注意,这是一个非常严格的 TS 实现。
import { deleteCookie, hasCookie } from 'cookies-next'
import { GetServerSideProps } from 'next'
export function withAuth(gssp: GetServerSideProps) {
return async ctx => { // error 1
const { req, res } = ctx
const hasToken = hasCookie('token', { req, res })
if (!hasToken) {
deleteCookie('token', { req, res })
deleteCookie('user', { req, res })
return {
redirect: {
destination: '/login',
permanent: false,
},
props: {},
}
}
const gsspData = await gssp(ctx)
return {
props: {
...gsspData?.props, // error 2
hasToken,
},
}
}
}
// error-1:
Parameter 'ctx' implicitly has an 'any' type.ts(7006)
// error-2:
Property 'props' does not exist on type 'GetServerSidePropsResult<{ [key: string]: any; }>'.
Property 'props' does not exist on type '{ redirect: Redirect; }'.ts(2339)
这也是有错误的实现:
export const getServerSideProps: GetServerSideProps = withAuth(ctx => { // error at CTX
return { props: {} }
})
// error-3
Argument of type '(ctx: GetServerSidePropsContext<ParsedUrlQuery, PreviewData>) => { props: {}; }' is not assignable to parameter of type 'GetServerSideProps<{ [key: string]: any; }, ParsedUrlQuery, PreviewData>'.
Type '{ props: {}; }' is missing the following properties from type 'Promise<GetServerSidePropsResult<{ [key: string]: any; }>>': then, catch, finally, [Symbol.toStringTag]ts(2345)
任何关于此事的启示将不胜感激。提前致谢。
【问题讨论】:
标签: reactjs typescript next.js server-side-rendering