我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。
我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。
我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
当前回答
你想要创建一个自定义定义,并使用Typescript中称为声明合并的特性。这是常用的,例如在方法重写中。
创建一个custom.d.ts文件,并确保将其包含在tsconfig中。Json的文件节(如果有的话)。内容如下所示:
declare namespace Express {
export interface Request {
tenant?: string
}
}
这将允许你在代码的任何地方使用这样的东西:
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)
})
其他回答
所有这些回答在某种程度上似乎都是错误的或过时的。
这在2020年5月对我有效:
在$ {PROJECT_ROOT} / @types /快递/ index.d.ts:
import * as express from "express"
declare global {
namespace Express {
interface Request {
my_custom_property: TheCustomType
}
}
}
在tsconfig。Json,添加/合并属性,使:
"typeRoots": [ "@types" ]
欢呼。
他们提供的解决方案没有一个对我有效。我最终只是扩展了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 = '';
}
现在回答这个问题可能已经很晚了,但无论如何,我是这样解决的:
确保在tsconfig文件中包含了类型的源代码(这可能是一个全新的线程) 在types目录中添加一个新目录,并将其命名为要为其扩展或创建类型的包。在本例中,您将创建一个名为express的目录 在express目录中创建一个文件,并将其命名为index.d.ts(必须与此完全相同) 最后,为了扩展类型,你只需要放如下代码:
declare module 'express' {
export interface Request {
property?: string;
}
}
也许这个问题已经有了答案,但我想分享一点, 有时候,像其他答案这样的界面可能有点太严格了, 但我们实际上可以维护所需的属性,然后通过创建值为any的字符串类型的键来添加任何要添加的其他属性
import { Request, Response, NextFunction } from 'express'
interface IRequest extends Request {
[key: string]: any
}
app.use( (req: IRequest, res: Response, next: NextFunction) => {
req.property = setProperty();
next();
});
现在,我们还可以向这个对象添加任何我们想要的属性。
如果您正在寻找与express4一起工作的解决方案,下面是:
@types /快递/ index.d。--------必须是/index.d.ts
declare namespace Express { // must be namespace, and not declare module "Express" {
export interface Request {
user: any;
}
}
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "es2016",
"typeRoots" : [
"@types", // custom merged types must be first in a list
"node_modules/@types",
]
}
}
参考资料来自https://github.com/TypeStrong/ts-node/issues/715#issuecomment-526757308