10

when I write this:

import { Request } from 'express-serve-static-core';

router.post((req: Request, res, next) => {
  req.session.user = user;
}

tsc gives me an error:

'Object is possibly 'undefined'.

I know the original Request type does not have the session field.

I check @types/express-session index.d.ts file, found this:

declare global {
  namespace Express {
    interface Request {
      session?: Session;
      sessionID?: string;
    }
  //....
}

So I want to add extra field session and sessionID type to the req.

How can I use ? like this: req: Request & ExpressSessionRequest.

So the req will have both original Request type and extra fields type which @types/express-session add.

slideshowp2
  • 38,463
  • 29
  • 127
  • 255

1 Answers1

15

The problem is not that Request does not have the session or sessionID properties -- the typings for express-session already adds the properties to Request interface via declaration merging.

The error comes from turning the strictNullChecks compiler option on. Since the properties session is declared as nullable in the type definition, the compiler warns you exactly that. If you are sure that req.session is not null of undefined, you can use the not-null assertion operator (!) to suppress the error:

router.post((req: Request, res, next) => {
    req!.session!.user = user;
})

Or check for null|undefined explicitly:

router.post((req: Request, res, next) => {
    if (req.session) {
        req.session.user = user;
    }
})

If you want to make the session and sessionID properties non-nullable, then you can write your own custom type:

type YourSessionRequest = Request & {
    session: Express.Session;
    sessionID: string;
}
router.post((req: YourSessionRequest, res, next) => {
    req.session.user = user;
})
Saravana
  • 28,153
  • 11
  • 81
  • 94
  • yes. my mistake. I forget the `session` and `sessionID` are optional properties. But does it make sense? I always think the `session` and `sessionID` properties are always exist on `req` when use `express-session` . – slideshowp2 Aug 23 '17 at 04:00
  • 1
    I am not sure `express-session`. If the `session` and `sessionID` properties always exist then the typings need to be updated. If you want to override the properties yourself, you can try the option in my updated answer. – Saravana Aug 23 '17 at 04:08