【问题标题】:What is the correct type for this handler此处理程序的正确类型是什么
【发布时间】:2021-04-21 07:09:39
【问题描述】:

我在“选择”这个函数的正确类型时遇到了麻烦。它是 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 会显示此错误

【问题讨论】:

    标签: node.js typescript express eslint


    【解决方案1】:

    那是因为RequestHandler 接口期望函数返回 void,但您的 post 函数返回 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>;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-15
      • 2011-04-16
      • 2021-07-12
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多