Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare typescript interface extension to node request session object?

In the following, returnTo is added to the session object by my passport methods. How do I declare its 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);
};
like image 637
Joseph Avatar asked Jul 08 '15 21:07

Joseph


2 Answers

There's a type declaration for express-session on DefinitelyTyped:

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

Following the pattern in that file, you can create a new d.ts (call it whatever you want) containing:

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

TypeScript will "merge" this extra property into the existing definitions.

like image 68
Daniel Earwicker Avatar answered Nov 17 '22 01:11

Daniel Earwicker


Just create a generic T and passed instead of request

<T extends {session: {user: any}}, Request>(sessionRequest: T) => {}
like image 44
Camilo Azula Avatar answered Nov 17 '22 00:11

Camilo Azula