【发布时间】: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