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