How to declare a typescript extension for the node interface of a request session object?

Further, it is returnToadded to the session object using my passport methods. How to declare your interface in typescript?

import express = require('express');
import expressSession = require('express-session');

// how to declare presence of returnTo, which is not in underlying type?

export function createSession(req: express.Request, res: express.Response, next: Function) {

  passport.authenticate('local', (err: any, user: UserInstance, info: any) => {
    //. . .
    req.logIn(user, (err) => {
      //. . .
      res.redirect(req.session.returnTo || '/');
    });
  })(req, res, next);
};
+4
source share
2 answers

In the type declaration for express-sessionon DefinitelyTyped:

https://github.com/borisyankov/DefinitelyTyped/blob/master/express-session/express-session.d.ts

Following the template in this file, you can create a new one d.ts(name it whatever you want):

declare module Express {
  export interface Session {
    returnTo: string;
  }
}

TypeScript will merge this additional property into existing definitions.

+5
source

Just create a generic T and pass instead of a query

<T extends {session: {user: any}}, Request>(sessionRequest: T) => {}
+2
source

All Articles