Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 532
Mr. Smith Avatar asked Aug 11 '16 15:08

Mr. Smith


3 Answers

May be due to the package version, the answer @Vitalii Zurian provided is not working for me. If you want to extend session data on req.session and pass the TSC type checks, you should extend SessionData interface.

E.g.

User.ts:

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

export = User;

app.ts:

import express from 'express';
import User from './User';

declare module 'express-session' {
  interface SessionData {
    user: User;
  }
}

function controller(req: express.Request, res: express.Response) {
  req.session.user;
}

package versions:

"express": "^4.17.1",
"express-session": "^1.17.1",
"@types/express-session": "^1.17.3",
"@types/express": "^4.17.11",
"typescript": "^3.9.7"

result:

enter image description here

like image 118
slideshowp2 Avatar answered Oct 16 '22 19:10

slideshowp2


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
    }
  }
}
like image 23
Vitalii Zurian Avatar answered Oct 16 '22 20:10

Vitalii Zurian


For me types.express-session.d.ts:

declare namespace Express {
    interface CustomSessionFields {
        myCustomField: string
    }

    export interface Request {
        session: Session & Partial<SessionData> & CustomSessionFields
    }
}

This answer relates with this post

like image 1
MiF Avatar answered Oct 16 '22 20:10

MiF