javascriptnode.jstypescriptexpresssession

Property `user` does not exist on type `Session & Partial<SessionData>`


I had a code in javascript and I'm trying to convert it to typescript

route.get('/order', async(req,res) => {  
    var sessionData = req.session;
    if(typeof sessionData.user === 'undefined')
    {        
        res.redirect('/panel/login');
    }    

this is a piece of my code that used to work correctly in javascript but now I get this error for the user:

Property 'user' does not exist on type 'Session & Partial'

I assume I should add types for the sessionData variable and (req, res) params but I don't know what type should exactly be assigned to it.

PS: I know this question looks duplicated but I've tried solutions from other similar questions and it didn't work

any help would be appreciated.


Solution

  • As stated in the express-session types comment, you have to use Declaration merging.

    Here's how you can implement Declaration merging on express-session:

    import session from 'express-session';
    
    declare module 'express-session' {
      export interface SessionData {
        user: { [key: string]: any };
      }
    }