typescript - La propiedad X no existe en el tipo 'GetServerSidePropsContext'
Tengo lo siguiente:
type Session = {
bearer: string,
firstName: string,
lastName: string,
etc...
};
interface ServerContext extends GetServerSidePropsContext {
session: Session,
};
export type ServerProps<P extends { [key: string]: any } = { [key: string]: any }> = (
context: ServerContext
) => Promise<GetServerSidePropsResult<P>>;
export const requireAuth = (gssp: GetServerSideProps) => {
return async (ctx: GetServerSidePropsContext) => {
const { req } = ctx;
const session = req?.headers?.cookie ? await getSession(req?.headers?.cookie) : null;
if (!session) {
return {
redirect: { permanent: false, destination: '/login' }
};
};
const serverSession = { ...ctx, session };
return await gssp(serverSession);
};
};
Y luego, siempre que sea necesario, lo utilizo de la siguiente manera:
export const getServerSideProps: ServerProps = requireAuth(async _ctx => {
const { session } = _ctx;
let account = session;
let stats = {};
try {
stats = fetchSomeData
} catch (error) {
console.log('Pages/Index Fetching Error: ', error);
}
return {
props: {
account: account,
stats: stats,
navbar: true,
footer: true,
},
};
});
Problema: const { session }=_ctx produce el siguiente error: "La propiedad session no existe en el tipo 'GetServerSidePropsContext
Solución alternativa: Si voy a node_modules/next/types/index.d.tsx y simplemente agrego session: Session a GetServerSidePropsContext, funciona perfectamente, pero si intento extender la interfaz como arriba, no parece funcionar.
Respuesta #1
export const requireAuth = (gssp: ServerProps) => {
return async (ctx: GetServerSidePropsContext) => {
const { req } = ctx;
const session = req?.headers?.cookie ? await getSession(req?.headers?.cookie) : null;
if (!session) {
return {
redirect: { permanent: false, destination: '/login' }
};
};
const serverSession = { ...ctx, session };
return await gssp(serverSession);
};
};
Deberías haber usado ServerProps en lugar de GetServerSideProps
