Lin Du
Lin Du

Reputation: 102327

How to use @types/express-session?

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.

Upvotes: 14

Views: 16519

Answers (1)

Saravana
Saravana

Reputation: 40604

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

Upvotes: 20

Related Questions