【问题标题】:Data type of function in TypeScriptTypeScript 中函数的数据类型
【发布时间】:2021-09-09 04:26:48
【问题描述】:

我应该在:之后为这个函数添加什么样的数据?

public saveHistory(log: String): "HERE!" {
  return async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => {
    try {
      ...
    } catch (e) {
      ...
    }
  };
}

【问题讨论】:

  • 我认为是(req: Request, res: Response, next: NextFunction) =&gt; Promise&lt;Response | void&gt;
  • 不,是类的方法

标签: typescript express types


【解决方案1】:
(req: Request, res: Response, next: NextFunction) => Promise<Response | void>

您已经在 return 语句中列出了它,但没有 async(您已经返回了一个 Promise)并且函数返回的语法从 : 切换到 =&gt;。但是,在大多数情况下(包括这种情况),您也可以省略 : 并允许 TypeScript 从您的 return 语句中推断出您的返回类型。

function saveHistory(log: String):
    (req: Request, res: Response, next: NextFunction) => Promise<Response | void> {
  return async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => {
    try {
      // ...
    } catch (e) {
      // ...
    }
  };
}

Playground Link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-03
    • 2019-06-06
    • 2016-02-28
    • 2020-05-17
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多