【问题标题】:Express router requests with custom expected fields带有自定义预期字段的快速路由器请求
【发布时间】:2021-03-22 12:01:45
【问题描述】:

我正在将基于 JS 的 express 应用程序重写为 Typescript。在重构路由器实例时,我偶然发现了以下问题:

this.router.get('/tenantInfo', (req, res) => {
  res.send(this.getTentantInfo(req.tenant))
})

当我想把它转换成 Typescript 时,它看起来像这样:

import express, { Request, Response, Router } from 'express'

this.router.get('/tenantInfo', (req: Request, res: Response) => {
  res.send(this.getTentantInfo(req.tenant))
})

这会导致req.tenant 出现错误,因为Request 没有此属性。我搜索了 Stackoverflow 并找到了 this answer,但是,我认为如果我只是将 express 的 Request 接口扩展为我将要使用的每个 每个附加属性,这不会导致良好的应用程序结构期待在我的应用程序的各个地方

以干净且可维护的方式解决此问题的好方法是什么?

【问题讨论】:

  • 扩展Request 接口是要走的路。 ...if I just extend the Request interface of express with each and every additional property that I will expect in various places of my application,这就是 TypeScript 的意义所在!

标签: typescript express typescript-declarations


【解决方案1】:

您可能需要在使用之前检查tenant,例如:

this.router.get('/tenantInfo', (req: Request, res: Response) => {
  if(req.tenant){
      res.send(this.getTentantInfo(req.tenant))
  }

  res.send({
     message: "Your error message..."      
  })
})

我不确定,但测试一下它是否能解决您的问题

【讨论】:

  • 这将是该问题的 JS 解决方案,以防止运行时问题。但在这种情况下,if 子句与之前的错误相同
【解决方案2】:

这可能不会增加我的评论,但您也可以将.d.ts 文件分隔到多个位置。假设你有这个目录结构

.
└── src
    ├── tenant
    │   ├── request.d.ts
    │   └── routes.ts
    ├── some
    │   ├── interface.ts
    │   ├── some.d.ts
    │   └── routes.ts
    ├── other
    │   └── ...
    └── stuff
        └── ...

tenant/request.d.ts

declare namespace Express {
  interface Request {
    tenant?: string;
  }
}

some/interface.ts

export interface Some {
  foo: string;
  bar: string;
}

some/request.d.ts

import { Some } from "./interfaces"; 

declare namespace Express {
  interface Request {
    some?: Some;
  }
}

otherstuff 也是如此...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 2015-06-02
    • 2019-01-01
    • 2018-01-11
    • 1970-01-01
    相关资源
    最近更新 更多