转到主要内容
版本:4.x

TypeScript

从 v3 开始,Socket.IO 现在对TypeScript具有很好的支持。

服务器

首先,声明一些类型:

interface ServerToClientEvents {
noArg: () => void;
basicEmit: (a: number, b: string, c: Buffer) => void;
withAck: (d: string, callback: (e: number) => void) => void;
}

interface ClientToServerEvents {
hello: () => void;
}

interface InterServerEvents {
ping: () => void;
}

interface SocketData {
name: string;
age: number;
}

并在创建服务器时使用它们:

const io = new Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData>();

然后,从 IDE 的帮助中获益!

ServerToClientEvents在发送和广播事件时使用接口中声明的事件:

io.on("connection", (socket) => {
socket.emit("noArg");
socket.emit("basicEmit", 1, "2", Buffer.from([3]));
socket.emit("withAck", "4", (e) => {
// e is inferred as number
});

// works when broadcast to all
io.emit("noArg");

// works when broadcasting to a room
io.to("room1").emit("basicEmit", 1, "2", Buffer.from([3]));
});

ClientToServerEvents接收事件时使用接口中声明的那些:

io.on("connection", (socket) => {
socket.on("hello", () => {
// ...
});
});

接口中声明的InterServerEvents用于服务器间通信(于socket.io@4.1.0添加):

io.serverSideEmit("ping");

io.on("ping", () => {
// ...
});

最后,SocketData type 用于键入 socket.data 属性 (于socket.io@4.4.0添加):

io.on("connection", (socket) => {
socket.data.name = "john";
socket.data.age = 42;
});
警告

这些类型提示不会取代输入的正确验证/清理。像往常一样,永远不要相信用户输入。

客户端

在客户端,您可以重用相同的ServerToClientEventsClientToServerEvents 接口:

import { io, Socket } from "socket.io-client";

// please note that the types are reversed
const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io();

同样,在ClientToServerEvents发送事件时使用接口中声明的事件:

socket.emit("hello");

ServerToClientEvents并且在接收事件时使用声明的那些:

socket.on("noArg", () => {
// ...
});

socket.on("basicEmit", (a, b, c) => {
// a is inferred as number, b as string and c as buffer
});

socket.on("withAck", (d, callback) => {
// d is inferred as string and callback as a function that takes a number as argument
});