路由中调用函数"/>
在返回中间件的快速路由中调用函数
我正在创建一个自定义函数来处理 API 请求验证。它是这样完成的:
export function validateBody(schema: string): (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void {
return function (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction): void | ExpressResponse {
// Some operation
next();
}
}
它在 api 路由中用作返回中间件的函数调用
router.route('/api/users/currentuser').get(validateBody('signIn'), (req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => {
我收到以下 lint 错误
No overload matches this call.
The last overload gave the following error.
Argument of type '(req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
Type '(req: ExpressRequest, res: ExpressResponse, next: ExpressNextFunction) => void' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
Types of parameters 'req' and 'req' are incompatible.
Property 'value' is missing in type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' but required in type 'ExpressRequest'.ts(2769)
types.ts(4, 5): 'value' is declared here.
index.d.ts(222, 5): The last overload is declared here.
它期待我尝试使用的“RequestHandleParam”类型,但它开始在“validateBody”函数定义中抛出错误。非常感谢任何解决方案或解决方法。
Ps: 使用 javascript 而不是 typescript 可以按预期工作。
回答如下:使用起来更简单的接口是RequestHandler。它隐式地键入了所有请求处理程序函数参数,这减少了很多样板文件
import { RequestHandler } from "express";
const validateBody =
(schema: string): RequestHandler =>
(_req, _res, next) => {
next();
};
更多推荐
在返回中间件的快速路由中调用函数
发布评论