gpt4 book ai didi

node.js - 类型为 '(req: Request, res: IResponse, next: NextFunction) => void' 的参数不可分配给类型为 'PathParams' 的参数与 express.js

转载 作者:行者123 更新时间:2023-12-03 12:13:52 25 4
gpt4 key购买 nike

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

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.

最佳答案

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;

关于node.js - 类型为 '(req: Request, res: IResponse, next: NextFunction) => void' 的参数不可分配给类型为 'PathParams' 的参数与 express.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58200432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com