作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个路由处理程序,我想将它添加到我的路由中:
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/
这是我的中间件: export const isLogged = () => (req: Request, res: Response, next: NextFunction) => next();
我正在创建一个路由处理程序,我想将它添加到我的路由中: import { Request, Response, NextFunction } from "express"; interface IRe
我是一名优秀的程序员,十分优秀!