我为getServerSideProps在Next.js中创建了一个auth包装器。我在钩子和需要它的页面上有一些类型错误。下面是包装器代码,后面跟着TypeScript错误。请注意,这是一个非常严格的TypeScript实现。
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)任何关于这件事的说明都将不胜感激。
发布于 2022-10-23 16:24:34
有一个缺失的显式类型,某些类型的缩小需要碰巧使TypeScript高兴。
对于第一个错误,因为您使用的是严格的类型,所以TypeScript会抱怨ctx是any的隐式类型。您可以使用GetServerSidePropsContext正确地键入ctx。
对于第二个错误,TypeScript无法自行确定gsspData的正确类型(可能的类型之外),因此我们可以通过使用'props' in gsspData ? gsspData.props : {}缩小它的范围来帮助解决这个问题。这种缩小确保了props在gsspData中的存在,这样我们就可以安全地调用gsspData.props。
import { deleteCookie, hasCookie } from 'cookies-next'
import { GetServerSideProps } from 'next'
export function withAuth(gssp: GetServerSideProps) {
// Explicitly type `ctx` as `GetServerSidePropsContext`
return async (ctx: GetServerSidePropsContext) => {
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
}
// No need to return `props` when redirecting
}
}
const gsspData = await gssp(ctx)
return {
props: {
// Narrow down `gsspData` type
...('props' in gsspData ? gsspData.props : {}),
hasToken
}
}
}
}最后,传递给withAuth的函数需要返回一个承诺(因为它被键入为gssp: GetServerSideProps)。我们可以通过使函数async来简单地修复错误。
export const getServerSideProps: GetServerSideProps = withAuth(async (ctx) => {
// Your logic here
return { props: {} }
})https://stackoverflow.com/questions/73886739
复制相似问题