如何为express-session扩展自定义Session类型并添加isAuth等字段
如何扩展Express-Session的自定义Session类型?
要解决将自定义字段添加到Express Session并摆脱any类型的问题,你可以按照以下步骤操作:
1. 定义自定义Session相关接口
先明确你需要的字段结构,先定义userinfo的类型,再继承Express-Session的原生Session类型创建自定义Session接口:
// 定义userinfo的结构 interface UserInfo { sub: string; name: string; family_name: string; given_name: string; picture: string; email: string; } // 自定义Session接口,继承原生Session类型 interface CustomSession extends Session { access_token?: string; userinfo?: UserInfo; isAuth?: boolean; }
2. 扩展Express的Request类型
通过TypeScript的模块扩展特性,让Express的Request对象的session属性指向我们的自定义类型:
declare module 'express' { interface Request { session: CustomSession; } } // 适配部分版本的express-session,可同时添加 declare module 'express-session' { interface SessionData extends CustomSession {} }
注意:这些类型定义建议放在单独的类型文件中(比如src/types/express-session.d.ts),并确保在tsconfig.json的include数组中包含该文件。
3. 修改业务代码,移除any类型
现在你可以安全地在代码中使用自定义Session类型,不用再依赖any:
赋值Session字段
// 假设access_token和Userinformation已提前获取 req.session.access_token = access_token; req.session.userinfo = Userinformation; req.session.isAuth = true; // 保存session
修复权限验证中间件
import { Request, Response, NextFunction } from 'express'; const isAuth = (req: Request, res: Response, next: NextFunction) => { // 此时req.session.isAuth会被正确识别为boolean|undefined类型 if (req.session.isAuth) { next(); } else { res.render("landing"); } };
这样处理后,TypeScript就能正确推断Session字段的类型,既摆脱了any的不安全性,也满足了自定义字段的需求。
内容的提问来源于stack exchange,提问作者Shen Zhenhua
相关产品推荐
相关产品推荐

