Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tie socket.io width express an TypeScript?

On the server, I am trying to bind express to socket.io, however, when connecting socket.io, I get the following error in the IDE:

TS2349: This expression is not callable.
Type 'typeof import("***/node_modules/socket.io/dist/index")' has no call signatures.

Code in server.ts:

import * as express from 'express';
import * as http from 'http';
import * as socketIo from 'socket.io';

const app: express.Express = express();
const httpServer: http.Server = new http.Server(app);
const io: any = socketIo();
const port: string | number = process.env.PORT || 3000;

app.use(express.static('public'));

const server: any = httpServer.listen(port, (): void => {
  console.log('listening on *:3000');
});
like image 826
Uolary Avatar asked Jan 25 '26 22:01

Uolary


1 Answers

because you are using ES Modules to import your dependencies, the caller syntax is a little bit different due to the way ESM loads exported functions/methods.

i created a local example and inspecting socket.io types, the correct way of using it with TypeScript looks like:

import * as express from "express";
import * as http from "http";
import * as socketio from "socket.io";

const app = express.default();

app.get("/", (_req, res) => {
  res.send({ uptime: process.uptime() });
});

const server = http.createServer(app);
const io = new socketio.Server(server);

io.on("connection", (...params) => {
  console.log(params);
});

server.listen(4004, () => {
  console.log("Running at localhost:4004");
});

and my package.json is:

{
  "dependencies": {
    "@types/express": "4.17.11",
    "express": "4.17.1",
    "nodemon": "2.0.7",
    "socket.io": "4.0.0",
    "ts-node": "9.1.1",
    "typescript": "4.2.3"
  }
}
like image 190
oieduardorabelo Avatar answered Jan 28 '26 15:01

oieduardorabelo