【发布时间】:2021-03-14 15:47:12
【问题描述】:
我正在尝试使用 TypeScript 在 Express 中创建路由,因此我像往常一样将 createUser 函数的参数设置为 req: Request, res: Response 和 @987654326 @:NextFunction,显然来自@types/express。每次都有效,但这次显示错误:
No overload matches this call.
Overload 1 of 3, '(path: PathParams, ...handlers: RequestHandler<ParamsDictionary, any, any, ParsedQs>[]): Router', gave the following error.
Argument of type '(req: Request, res: Response, next: any) => Promise<any>' is not assignable to parameter of type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
Types of parameters 'req' and 'req' are incompatible.
Type 'Request<ParamsDictionary, any, any, ParsedQs>' is missing the following properties from type 'Request': cache, credentials, destination, integrity, and 15 more.
Overload 2 of 3, '(path: PathParams, ...handlers: RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>[]): Router', gave the following error.
Argument of type '(req: Request, res: Response, next: any) => Promise<any>' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'.
Type '(req: Request, res: Response, next: any) => Promise<any>' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
Overload 3 of 3, '(path: PathParams, subApplication: Application): Router', gave the following error.
Argument of type '(req: Request, res: Response, next: any) => Promise<any>' is not assignable to parameter of type 'Application'.
Type '(req: Request, res: Response, next: any) => Promise<any>' is missing the following properties from type 'Application': init, defaultConfiguration, engine, set, and 61 more.
如何解决这个问题? 这是应用程序的一些代码:
protected setupRoutes(): void {
this.router.post("/", this.createUser);
}
// Routes:
private async createUser(req: Request, res: Response, next): Promise<any> {
try {
res.status(200).send("Hi!");
} catch (err) {
return next({
status: err.status,
message: err.message,
});
}
}
【问题讨论】:
-
附带说明,如果您打算在
createUser中使用this,则最好将侦听器设置为this.createUser.bind(this)而不是this.createUser。 -
当然可以,谢谢!我忘了。 :>
标签: node.js typescript express