【问题标题】:Express TypeScript route propertiesExpress TypeScript 路由属性
【发布时间】: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


【解决方案1】:

我很惊讶这对你有用。 Express 有自己的类型可用于请求和响应,这些类型扩展了您正在使用的基本类型。

例如,这里是type definition of the express request

interface Request<P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.Request<P, ResBody, ReqBody, ReqQuery> { }

尝试使用这些类型:

import express from 'express';


const handleMyRequest = (req: express.Request, res: express.Response) => {
  // Whatever
}

【讨论】:

  • 我用过这些,但忘记从 Express 类型导入。现在它工作正常。谢谢。 :)
  • @Cholewka 很高兴为您提供帮助 :)
猜你喜欢
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 2019-07-03
相关资源
最近更新 更多