1、express 库的类型文件 .d.ts 文件类型描述不准确
    将鼠标悬浮在 req.bodypassword 上,编辑器给我们的类型注解是 any,那我们可以自己声明一个 interface ,继承 Request 的方法,额外的添加自己想添加的属性

    1. interface RequestWithBody extends Request {
    2. body: {
    3. // 做一个泛匹配
    4. [key: string]: string | undefined
    5. }
    6. }
    7. router.post('/getData', (req: RequestWithBody, res: Response) => {
    8. ...
    9. })

    2、当使用中间件的时候,对 req 或者 res 做了修改之后,实际上类型并不能改变
    index.ts 里 创建一个中间件

    1. ...
    2. app.use((req: Request, res: Response, next: NextFunction) => {
    3. req.studentName = 'zhuBingLin'
    4. next()
    5. })
    6. ...

    src 目录下创建一个 custom.d.ts 文件,在里面写入:

    1. declare namespace Express {
    2. interface Request {
    3. studentName: string
    4. }
    5. }

    利用 TS 的类型融合的机制,将自己写的和express的描述文件进行融合

    现在修改一下错误提示(router.ts):

    1. ...
    2. res.send(`${req.studentName}paassword Error!`)
    3. ...