我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。
我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。
我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):
app.use((req, res, next) => {
req.property = setProperty();
next();
});
当前回答
我已经改变了响应类型,包括ApiResponse(一个自定义响应对象)response <ApiResponse>
export interface ApiResponse {
status?: string
error?: string
errorMsg?: string
errorSubject?: string
response?: any
}
const User = async (req: Request, res: Response<ApiResponse>, next: NextFunction) => {
try {
if (!username) return res.status(400).send({ errorMsg: 'Username is empty' })
/* ... */
} catch(err){
/* ... */
}
}
其他回答
公认的答案(和其他答案一样)对我不适用,但是
declare module 'express' {
interface Request {
myProperty: string;
}
}
所做的。希望这能帮助到一些人。
他们提供的解决方案没有一个对我有效。我最终只是扩展了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 = '';
}
只需将属性添加到req。params对象。
req.params.foo = "bar"
现在回答这个问题可能已经很晚了,但无论如何,我是这样解决的:
确保在tsconfig文件中包含了类型的源代码(这可能是一个全新的线程) 在types目录中添加一个新目录,并将其命名为要为其扩展或创建类型的包。在本例中,您将创建一个名为express的目录 在express目录中创建一个文件,并将其命名为index.d.ts(必须与此完全相同) 最后,为了扩展类型,你只需要放如下代码:
declare module 'express' {
export interface Request {
property?: string;
}
}
在尝试了8个左右的答案,没有成功。我终于设法让它与jd291的评论指向3mards回购工作。
在基库中创建一个名为types/express/index.d.ts的文件。在信中写道:
declare namespace Express {
interface Request {
yourProperty: <YourType>;
}
}
并将其包含在tsconfig中。json:
{
"compilerOptions": {
"typeRoots": ["./types"]
}
}
那么你的属性应该在每个请求下都是可访问的:
import express from 'express';
const app = express();
app.get('*', (req, res) => {
req.yourProperty =
});