如何绑定 socket.io 宽度来表达 TypeScript?

Uol*_*ary 3 node.js socket.io

在服务器上,我尝试将express绑定到socket.io,但是,当连接socket.io时,我在IDE中收到以下错误:

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

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');
});
Run Code Online (Sandbox Code Playgroud)

oie*_*elo 14

因为您使用 ES 模块导入依赖项,所以由于 ESM 加载导出函数/方法的方式,调用者语法略有不同。

我创建了一个本地示例并检查socket.io类型,将其与 TypeScript 一起使用的正确方法如下所示:

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

Run Code Online (Sandbox Code Playgroud)

我的package.json是:

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

Run Code Online (Sandbox Code Playgroud)