Whenever I include the following code snippet:
import { Request } from 'express-serve-static-core';
router.post((req: Request, res, next) => {
req.session.user = user;
}
I encounter an error when running tsc
:
'Object is possibly 'undefined'.
I am aware that the original Request
type does not contain the session
field.
Upon inspecting the @types/express-session
index.d.ts
file, I discovered this:
declare global {
namespace Express {
interface Request {
session?: Session;
sessionID?: string;
}
//....
}
Therefore, I intend to add the extra fields session
and sessionID
with their respective types to the req
.
How can I achieve this? Can I do something like:
req: Request & ExpressSessionRequest
.
This would allow the req
to possess both the original Request
type as well as the additional fields introduced by @types/express-session
.