本文介绍了使用 Typescript 扩展 Express Request 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加一个属性来使用打字稿从中间件表达请求对象.但是我不知道如何向对象添加额外的属性.如果可能,我宁愿不使用括号表示法.

I’m trying to add a property to express request object from a middleware using typescript. However I can’t figure out how to add extra properties to the object. I’d prefer to not use bracket notation if possible.

我正在寻找一种解决方案,可以让我编写类似的内容(如果可能):

I’m looking for a solution that would allow me to write something similar to this (if possible):

app.use((req, res, next) => {
    req.property = setProperty();
    next();
});

推荐答案

您想创建自定义定义,并使用 Typescript 中名为 声明合并.这是常用的,例如在 method-override.

You want to create a custom definition, and use a feature in Typescript called Declaration Merging. This is commonly used, e.g. in method-override.

创建一个文件 custom.d.ts 并确保将其包含在您的 tsconfig.jsonfiles 部分(如果有).内容可以如下所示:

Create a file custom.d.ts and make sure to include it in your tsconfig.json's files-section if any. The contents can look as follows:

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

这将允许您在代码中的任何位置使用以下内容:

This will allow you to, at any point in your code, use something like this:

router.use((req, res, next) => {
    req.tenant = 'tenant-X'
    next()
})

router.get('/whichTenant', (req, res) => {
    res.status(200).send('This is your tenant: '+req.tenant)
})

这篇关于使用 Typescript 扩展 Express Request 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 09:54