1

I have this small piece of code

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}`);
});

I wonder why this message pop up

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)

I didn't declare type for req and res, but why typescript show error only for the err?

Judy Allen
  • 83
  • 1
  • 7
  • Looks like `listen` in the type definitions never takes an error parameter https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express-serve-static-core/index.d.ts#L1031-L1036 – Benjamin Gruenbaum Nov 19 '20 at 09:11
  • Looking at the node source code - it looks like indeed the callback is never called with an error and it's just `this.once('listening', cb);` - so the type definitions are actually correct here. – Benjamin Gruenbaum Nov 19 '20 at 09:15
  • An error would be sent via an `error` event on the server object returned from `app.listen()`. You can add a separate listener for the error event. – jfriend00 Nov 19 '20 at 09:40

1 Answers1

3

There is no error paramter.

Hold CTRL and then click on listen

It will open index.d.ts and you will see the definition

  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;

As you can see the callback takes no argument

bill.gates
  • 14,145
  • 3
  • 19
  • 47