【问题标题】:Unable to compile TypeScript - No overload matches this call无法编译 TypeScript - 没有重载匹配此调用
【发布时间】:2021-12-26 09:41:54
【问题描述】:

我正在使用带有 NodeJS 和 express 的 typescript。

    this.app.listen(port, (err: any) => {
      if (err) {
        console.log("err", err)
      } else {
        console.log(`Server is listing on port ${port}`);
      }
    });

他们上面的代码在 Visual Studio 代码中以及当我尝试编译打字稿时给了我错误。当我尝试编译打字稿时收到以下错误消息。

没有重载匹配这个调用。 最后一次重载出现以下错误。

'(err: any) => void' 类型的参数不可分配给 '() => void'.ts(2769) 类型的参数

index.d.ts(1205, 5):最后一个重载在这里声明。 块引用

我已经尝试了下面的代码:我仍然得到同样的错误。

this.app.listen(port, (err: any, req: express.Request, res: express.Response) 

我似乎无法理解为什么会收到此错误。提前致谢。

【问题讨论】:

  • this.app 的类型是什么?您的回调似乎不需要任何参数。
  • 感谢您的评论。 public app: express.Application;.

标签: javascript node.js typescript express


【解决方案1】:

listen 方法有五个重载可用。而且,他们都没有将回调作为(error) => void。见这里:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express-serve-static-core/ts4.0/index.d.ts#L1110-L1115

Permalink, if the above link does not work


    listen(port: number, hostname: string, backlog: number, callback?: () => void): http.Server;
    listen(port: number, hostname: string, callback?: () => void): http.Server;
    listen(port: number, callback?: () => void): http.Server;
    listen(callback?: () => void): http.Server;
    listen(path: string, callback?: () => void): http.Server;
    listen(handle: any, listeningListener?: () => void): http.Server;

因此,您必须执行以下操作:

 this.app.listen(port, () => {
  console.log(`Server is listing on port ${port}`);
});

也许是

 const server = this.app.listen(port, () => {
    console.log(`Server is listing on port ${port}`);
  });
 server.on('error', e => console.error("Error", e));

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2022-12-07
    • 2020-06-29
    • 2020-02-15
    • 2021-11-15
    • 2020-11-28
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    相关资源
    最近更新 更多