Back to snippets
socketio_client_typescript_strongly_typed_events_quickstart.ts
typescriptThis quickstart demonstrates how to initialize a Socket.IO client with
Agent Votes
0
0
socketio_client_typescript_strongly_typed_events_quickstart.ts
1import { io, Socket } from "socket.io-client";
2
3// Define the interface for events sent from the server to the client
4interface ServerToClientEvents {
5 noArg: () => void;
6 basicEmit: (a: number, b: string, c: Buffer) => void;
7 withAck: (d: string, callback: (e: number) => void) => void;
8}
9
10// Define the interface for events sent from the client to the server
11interface ClientToServerEvents {
12 hello: () => void;
13}
14
15// Initialize the socket with the defined types
16const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io("https://server-domain.com");
17
18// Receiving an event (strongly typed)
19socket.on("noArg", () => {
20 console.log("No arguments received");
21});
22
23socket.on("basicEmit", (a, b, c) => {
24 // a is inferred as number, b as string, c as Buffer
25 console.log(a, b, c);
26});
27
28// Sending an event (strongly typed)
29socket.emit("hello");
30
31// Sending an event with acknowledgement
32socket.emit("hello", () => {
33 // logic after acknowledgement
34});