Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 678
amir yeganeh Avatar asked Dec 02 '20 12:12

amir yeganeh


2 Answers

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 };
  }
}
like image 53
Kapobajza Avatar answered Nov 03 '22 20:11

Kapobajza


I just encountered the same issue as you. This seems to be a fairly recent issue: see explanation here.

To fix this I overloaded the module as described in the Github issue:

import "express-session";
declare module "express-session" {
  interface SessionData {
    user: string;
  }
}

Just replace string with whatever type you need for that field.

Also I have added ./typing-stubs in tsconfig.json

"typeRoots": [
      "./typing-stubs",
      "./node_modules/@types"
]
like image 19
Rabbit Avatar answered Nov 03 '22 20:11

Rabbit