类型'((req:Request,res:IResponse,next:NextFunction)=> void'的参数不能通过express.js分配给'PathParams'类型的参数

时间:2019-10-02 11:19:37

标签: node.js typescript express

我正在创建一个路由处理程序,我想将其添加到我的路由中:

import { Request, Response, NextFunction } from "express";

interface IResponse extends Response {
  error: (code: number, message: string) => Response;
  success: (code: number, message: string, result: any) => Response
}
const routeHandler = (req: Request, res: IResponse, next: NextFunction) => {
  res.error = (statusCode: number, errorMessage: string) => res.status(statusCode).json(errorMessage);
  res.success = (statusCode: number, message: string, result: any) => res.status(statusCode).json({
    message,
    result
  });
  return next();
};

export default routeHandler;

当我将此处理程序添加到路由索引文件时:

import { Router } from "express";
import routeHandler from "../utils/helpers";

const routes = Router();
routes.use(routeHandler);

export default routes;

我收到此错误:

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request, res: IResponse, next: NextFunction) => void' is not assignable to parameter of type 'PathParams'.
      Type '(req: Request, res: IResponse, next: NextFunction) => void' is missing the following properties from type '(string | RegExp)[]': pop, push, concat, join, and 25 more.ts(2769)
index.d.ts(55, 5): The last overload is declared here.

1 个答案:

答案 0 :(得分:1)

Express对您的界面IResponse一无所知。因此该方法无法匹配。

要实现您的想法,请使用module augmentation

import { Request, Response, NextFunction } from "express";

declare module 'express-serve-static-core' {
    interface Response {
        error: (code: number, message: string) => Response;
        success: (code: number, message: string, result: any) => Response
    }
}

const routeHandler = (req: Request, res: Response, next: NextFunction) => {
    res.error = (statusCode: number, errorMessage: string) => res.status(statusCode).json(errorMessage);
    res.success = (statusCode: number, message: string, result: any) => res.status(statusCode).json({
        message,
        result
    });
    return next();
};

export default routeHandler;