Express中Request泛型Locals类型的作用是什么?
Express Request泛型Locals的用途及req.auth扩展问题解析
你尝试通过Request的第五个泛型参数(Locals)定义req.auth属性却报错,核心原因是这个泛型并非用来扩展Request的顶层属性,而是专门约束req.locals对象的类型。
为什么你的代码报错?
Express的Request类型中,顶层属性(如req.auth)不属于Locals泛型的管辖范围。Locals泛型的作用是规范req.locals——这是Express官方预留的、用于中间件间传递自定义临时数据的容器,而非给req添加顶层属性的工具。
正确扩展req顶层属性的方式
若要给Request添加顶层的auth属性,需通过模块类型扩展修改Express的类型定义:
- 在项目中创建类型定义文件(比如
types/express.d.ts),写入以下内容:
declare namespace Express { interface Request { auth: { token: string; payload: object; }; } }
- 在
tsconfig.json中确保该类型文件被识别:
{ "compilerOptions": { "typeRoots": ["./node_modules/@types", "./types"] } }
Locals泛型的实际用法
当你需要在中间件间通过req.locals传递数据时,用这个泛型约束其类型,能获得精准的类型提示:
import { Request, Response, NextFunction } from "express"; interface RequestLocals { auth: { token: string; payload: object; }; } // 赋值中间件 const authMiddleware = (req: Request<{}, {}, {}, {}, RequestLocals>, res: Response, next: NextFunction) => { req.locals.auth = { token: "sample-token", payload: { userId: 1001 } }; next(); }; // 使用数据的中间件 const exampleMiddleware = (req: Request<{}, {}, {}, {}, RequestLocals>, res: Response) => { console.log(req.locals.auth.token); // 有正确的类型提示 res.send("处理完成"); };
内容的提问来源于stack exchange,提问作者Jaspper15325
相关产品推荐
相关产品推荐

