I am trying to add additional properties to session object
req.session.confirmationCode = confirmationCode;
but getting an error that confirmationCode property does not exist
Property 'confirmationCode' does not exist on type 'Session & Partial<SessionData>'.
I have index.d.ts file under types directory where I am adding this prop
declare global {
namespace session {
interface SessionData {
confirmationCode: number;
}
}
}
export {};
And this is my tsconfig.json file
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
"sourceMap": true,
"outDir": "./dist",
"moduleResolution": "node",
"removeComments": true,
"strict": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"resolveJsonModule": true,
"noImplicitAny": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noStrictGenericChecks": true
},
"exclude": ["node_modules"],
"include": ["src"]
}
I saw in source code for @types/express-session package that I can extend session object like
declare module "express-session" {
interface SessionData {
confirmationCode: number;
}
}
but when I do this, I get an error that session function is not callable
Type 'typeof import("express-session")' has no call signatures
How can I extend session object properly?
UPD1: And this is how I call session function
app.use(
session({
name: "wishlify",
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 60, // 2 months
secure: process.env.NODE_ENV === "production",
},
})
);
I found an answer in this question.
I added export {};
to index.d.ts file and this is now working as expected.
This line makes file not a script but a module.
The final version of index.d.ts file
declare module "express-session" {
interface SessionData {
confirmationCode: number;
}
}
export {};