如何绑定 socket.io 宽度表示 TypeScript?
How to tie socket.io width express an TypeScript?
在服务器上,我尝试将 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.
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');
});
因为您正在使用 ES 模块导入您的依赖项,调用方语法因 ESM 加载导出的方式而略有不同 functions/methods。
我创建了一个本地示例并检查了 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");
});
我的 package.json
是:
{
"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"
}
}
在服务器上,我尝试将 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.
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');
});
因为您正在使用 ES 模块导入您的依赖项,调用方语法因 ESM 加载导出的方式而略有不同 functions/methods。
我创建了一个本地示例并检查了 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");
});
我的 package.json
是:
{
"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"
}
}