我试图扩展Request类型以添加一个依赖于请求主体的属性,但是catchAsync
中的泛型没有被正确应用,并且它总是any
而不是传递的泛型参数index.d.ts
个
import {RequestHandler} from 'express';
import {ParamsDictionary} from 'express-serve-static-core';
import {ParsedQs} from 'qs';
export interface CustomFormData<T> {
data: T;
fileNames: string[];
buffers: Buffer[];
}
declare global {
namespace Express {
export interface Request<
P = ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = ParsedQs,
LocalsObj extends Record<string, any> = Record<string, any>,
> {
formData?: CustomFormData<ReqBody>;
}
}
}
字符串middleware.ts
个
import {Request, Response, NextFunction} from 'express';
export type AsyncRequestHandler<M> = (
req: Request<any, any, M, qs.ParsedQs, Record<string, any>>,
res: Response,
next: NextFunction,
) => Promise<void>;
export const catchAsync =
<M = any>(fn: AsyncRequestHandler<M>): AsyncRequestHandler<M>=>
async (req, res, next) => {
await fn(req, res, next);
if (res.headersSent) return;
next();
};
型controller.ts
个
postProduct = catchAsync<IPostProduct>(async (req, res) => {
const {data} = req.formData; // data is taken as "any" instead of "IPostProduct"
await ProductController._productService.create(data);
res.status(201).send();
});
型
2条答案
按热度按时间tkqqtvp11#
这是因为当你用泛型声明
AsyncRequestHandler
类型,然后将req
参数输入为Request<any, any, M, qs.ParsedQs, Record<string, any>>
时,它会从声明合并中获取默认的any
类型。有个办法字符串
如果采用这种方法,您实际上不需要声明合并,除非您希望
formData
在所有地方都可用,请注意,在其他地方,如果不使用中间件,它仍然是any
类型。4urapxun2#
我想出了一个稍微不优雅的解决方案,替换了
AsyncRequestHandler
中的formData
prop:字符串