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?
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:
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
}
}
}
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
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