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

问题描述

我正在尝试添加一个属性来表达来自使用typescript的中间件的请求对象。但是我无法弄清楚如何向对象添加额外的属性。如果可能,我更喜欢不使用括号符号。



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

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


解决方案

在TypeScript中,接口是开放式的。这意味着您可以通过重新定义来从任何地方添加属性。



考虑到您正在使用文件,您应该能够将请求界面重新定义为添加额外的字段。

  interface Request {
property:string;
}

然后在您的中间件功能中, strong> req 参数也应该有这个属性。您应该可以使用它,而不会对代码进行任何更改。


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();
});
解决方案

In TypeScript, interfaces are open ended. That means you can add properties to them from anywhere just by redefining them.

Considering that you are using this express.d.ts file, you should be able to redefine the Request interface to add the extra field.

interface Request {
  property: string;
}

Then in your middleware function, the req parameter should have this property as well. You should be able to use it without any changes to your code.

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

06-30 09:54