7

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

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried adding this definition into my // comment area above, but still get an error: src/server/controllers/sessionsController.ts(39,32): error TS2339: Property 'returnTo' does not exist on type 'Session'.
I get it - you have to have this definition in an external file. That works fine. Thanks!
That's right - stuff you declare in a module with exports/imports will not be global, and so won't merge with a pre-existing global declaration.
3

Just create a generic T and passed instead of request

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.