【发布时间】:2021-03-02 15:04:37
【问题描述】:
我有一小段代码
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显示错误?
【问题讨论】:
-
看起来类型定义中的
listen从不采用错误参数github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/… -
查看节点源代码 - 看起来确实回调从未被错误调用,它只是
this.once('listening', cb);- 所以这里的类型定义实际上是正确的。 -
将通过
error事件在从app.listen()返回的服务器对象上发送错误。您可以为错误事件添加单独的侦听器。
标签: javascript node.js typescript