使用Typescript扩展Express Request对象 [英] Extend Express Request object using Typescript
问题描述
我正在寻找一个解决方案,让我写出类似的内容(如果可能的话):
app.use((req,res,next)=> {
req.property = setProperty();
next();
});
在TypeScript中,接口是开放式的。这意味着您可以通过重新定义来从任何地方添加属性。
考虑到您正在使用 express.d.ts 文件,您应该能够将请求界面重新定义为添加额外的字段。
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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!