此处理程序的正确类型是什么
What is the correct type for this handler
我无法为该函数“选择”正确的类型。它是 express js 的异步处理程序。该项目使用 typescript 和 eslint 通过一些规则进行 linting
export function asyncHandler(
handler: any
): (req: Request, res: Response, next: NextFunction) => void {
return function (req: Request, res: Response, next: NextFunction): void {
Promise.resolve(handler(req, res, next)).catch(err => {
next(err);
});
};
}
如果我将处理程序更改为 handler: RequestHandler
,eslint 会显示此错误
那是因为 RequestHandler
接口期望函数 return 无效,但是你的 post
函数 return 是一个 Promise,因此错误。
这里是RequestHandler
的接口定义
export interface RequestHandler<
P = ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = ParsedQs,
Locals extends Record<string, any> = Record<string, any>
> {
// tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2)
(
req: Request<P, ResBody, ReqBody, ReqQuery, Locals>,
res: Response<ResBody, Locals>,
next: NextFunction,
): void;
}
在我看来,您可以继续使用 any
,因为它是您不必对类型约束过于严格的边缘情况之一。如果您仍想使用类型,可以生成自己的请求处理程序接口。
使用此接口,将消除 linter 错误:
interface AsyncRequestHandler {
(req: Request, res: Response, next: NextFunction): Promise<any>;
}
我无法为该函数“选择”正确的类型。它是 express js 的异步处理程序。该项目使用 typescript 和 eslint 通过一些规则进行 linting
export function asyncHandler(
handler: any
): (req: Request, res: Response, next: NextFunction) => void {
return function (req: Request, res: Response, next: NextFunction): void {
Promise.resolve(handler(req, res, next)).catch(err => {
next(err);
});
};
}
如果我将处理程序更改为 handler: RequestHandler
,eslint 会显示此错误
那是因为 RequestHandler
接口期望函数 return 无效,但是你的 post
函数 return 是一个 Promise,因此错误。
这里是RequestHandler
export interface RequestHandler<
P = ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = ParsedQs,
Locals extends Record<string, any> = Record<string, any>
> {
// tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2)
(
req: Request<P, ResBody, ReqBody, ReqQuery, Locals>,
res: Response<ResBody, Locals>,
next: NextFunction,
): void;
}
在我看来,您可以继续使用 any
,因为它是您不必对类型约束过于严格的边缘情况之一。如果您仍想使用类型,可以生成自己的请求处理程序接口。
使用此接口,将消除 linter 错误:
interface AsyncRequestHandler {
(req: Request, res: Response, next: NextFunction): Promise<any>;
}