首页 > 解决方案 > express typescript err throw 'any' 警告

问题描述

我有一小段代码

import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('The sedulous hyena ate the antelope!');
});

app.listen(port, err => { //show error here
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

我想知道为什么会弹出这个消息

No overload matches this call.
  The last overload gave the following error.
    Argument of type '(err: any) => void' is not assignable to parameter of type '() => void'.ts(2769)

我没有为 req 和 res 声明类型,但是为什么 typescript 只为 err 显示错误?

标签: javascriptnode.jstypescript

解决方案


没有错误参数。

按住 CTRL 然后点击listen

它将打开index.d.ts,您将看到定义

  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;

如您所见,callback没有参数


推荐阅读