我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。
我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。
我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
当前回答
只需将属性添加到req。params对象。
req.params.foo = "bar"
其他回答
这个答案将有利于那些依赖npm包ts-node的人。
我也在与扩展请求对象同样的问题作斗争,我在堆栈溢出中遵循了许多答案,并以遵循下面提到的策略结束。
我在以下目录中声明了express的扩展类型。$ {PROJECT_ROOT} / api / @types /快递/ index.d.ts
declare namespace Express {
interface Request {
decoded?: any;
}
}
然后更新我的tsconfig。Json变成这样。
{
"compilerOptions": {
"typeRoots": ["api/@types", "node_modules/@types"]
...
}
}
即使在执行上述步骤之后,visual studio也不再抱怨,但不幸的是,ts-node编译器仍然习惯抛出。
Property 'decoded' does not exist on type 'Request'.
显然,ts-node无法定位请求对象的扩展类型定义。
最终,在花了几个小时后,我知道VS Code并没有抱怨,并且能够找到类型定义,这意味着ts-node编译器有问题。
正在更新包中的开始脚本。Json为我解决了这个问题。
"start": "ts-node --files api/index.ts",
——files参数在这里起着关键作用,确定自定义类型定义。
欲了解更多信息,请访问:https://github.com/TypeStrong/ts-node#help-my-types-are-missing
如果你尝试了所有的答案,仍然没有得到工作,这里有一个简单的hack
app.use((req, res, next) => {
(req as any).property = setProperty();
next();
});
这将把req对象转换为任意类型,因此您可以添加任何想要的属性。 请记住,这样做将失去req对象的类型安全性。
公认的答案(和其他答案一样)对我不适用,但是
declare module 'express' {
interface Request {
myProperty: string;
}
}
所做的。希望这能帮助到一些人。
我用了回应。当地人反对储存新财产。下面是完整的代码
export function testmiddleware(req: Request, res: Response, next: NextFunction) {
res.locals.user = 1;
next();
}
// Simple Get
router.get('/', testmiddleware, async (req: Request, res: Response) => {
console.log(res.locals.user);
res.status(200).send({ message: `Success! ${res.locals.user}` });
});
他们提供的解决方案没有一个对我有效。我最终只是扩展了Request接口:
import {Request} from 'express';
export interface RequestCustom extends Request
{
property: string;
}
然后使用它:
import {NextFunction, Response} from 'express';
import {RequestCustom} from 'RequestCustom';
someMiddleware(req: RequestCustom, res: Response, next: NextFunction): void
{
req.property = '';
}
编辑:根据你的tsconfig,你可能需要这样做:
someMiddleware(expressRequest: Request, res: Response, next: NextFunction): void
{
const req = expressRequest as RequestCustom;
req.property = '';
}