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.
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 };
}
}
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"
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With