问题
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?
回答1:
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
}
}
}
回答2:
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:
来源:https://stackoverflow.com/questions/38900537/typescript-extend-express-session-interface-with-own-class