Issue
I am new to Typescript, Node as well as Express. I setup my project exactly as described here: https://www.digitalocean.com/community/tutorials/setting-up-a-node-project-with-typescript
This is the code, I am trying to run which I got from that link:
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 => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
When I try to run this code using npm start
, I get this error:
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 checked the .d.ts
file and saw that the callback takes no arguments. Someone else faced the same issue with this code here: express typescript err throw 'any' warning
I then read the comments on the original post where I got this post from and someone had mentioned that the code works if they change the first line from import express from 'express';
to var express = require('express');
Why does this happen? I also had to explicitly mention the types of req, res and err as any to make it work. This is the final code that works:
var express = require('express');
const app = express();
const port = 3000;
app.get('/', (req: any, res: any) => {
res.send('The sedulous hyena ate the antelope!');
});
app.listen(port, (err: any) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
Solution
When you get the No overload matches this call.
error, means you are defining parameters that do not exist on that type.
In your case, you have the err
parameter on listen
callback which should not be there (see http://expressjs.com/en/api.html under app.listen)
To fix the ts error, just remove the err and related code below.
Regarding your imports, I would suggest to keep them with the newer sintax instead of the old require (that should now work just fine).
Last but not least, try to always avoid setting your types as any
, as that is like having a fire alarm without batteries. The types you are looking for are express built-in and you can define them as such:
app.get('/', (req: express.Request, res: express.Response) => {
res.send('The sedulous hyena ate the antelope!');
});