Search code examples
node.jsexpresstypescriptnpmexpress-session

TypeScript: Extend Express.Session interface with own class


I'm working on a Typescript project with npm packages. I want to add a property to the Express.Session interface.

example Class:

class User {
    name: string;
    email: string;
    password: string;
}

export = User;

New d.ts file for the interface definition (don't want to edit express-session.d.ts):

declare namespace Express {
    interface Session {
        user: User
    }
}

app.ts

import User = require('./User');

function (req: express.Request, res: express.Response) {
    req.session.user //I want to use it like this.
}

the problem is, that User is not known in de d.ts file. But neither require nor import the User-file fixes that.

How can I add my own class to the session interface?


Solution

  • A bit late to the party, but it should be possible to import your interface to the definitions file

    import { User } from '../models/user';
    
    declare global {
      namespace Express {
        interface Session {
          _user?: User
        }
      }
    }