How to use @types/express-session?

slideshowp2 picture slideshowp2 · Aug 23, 2017 · Viewed 10k times · Source

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.

Answer

Saravana picture Saravana · Aug 23, 2017

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;
})