迁移Express应用到TypeScript时,扩展Request对象添加req.payload报TS2339错误的问题咨询
迁移Express应用到TypeScript时,扩展Request对象添加req.payload报TS2339错误的问题咨询
大家好,我最近正在把一个Express应用迁移到TypeScript,遇到了个棘手的问题——我有个中间件需要往request对象里存一些信息,比如req.payload,但TypeScript一直报错。
先给大家看一下我简化后的代码:
// server.ts import { Application } from 'express'; import { Request, Response, NextFunction } from 'express'; import express from 'express'; const app: Application = express(); function middleware1(req: Request, res: Response, next: NextFunction) { req.payload = { name: 'bob', }; next(); } app.use(middleware1); app.get('/', (req, res, next) => { res.json({ message: 'hello world' }); }); const PORT = process.env.PORT || 5005; app.listen(PORT, () => { console.log(`Server listening on port http://localhost:${PORT}`); });
当我尝试给req.payload赋值时,TypeScript抛出了这样的错误:
Property 'payload' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.(2339)
我知道需要扩展Express的Request类型,让它能识别这个自定义的payload属性,但试了几种方法都没搞定,有没有有经验的朋友能教教我具体该怎么配置或者修改代码呀?
备注:内容来源于stack exchange,提问作者ludovico
相关产品推荐
相关产品推荐

