Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Integration with Frameworks

Typed Events with TypeScript

Type Socket.IO events end to end with four interfaces, share them between server and client, type acknowledgements and socket.data, and validate at runtime.

Socket.IO events are strings with loosely shaped payloads. In plain JavaScript, a typo in an event name ("mesage") or a wrong argument order fails silently at runtime. TypeScript can catch these mistakes while you type. Socket.IO's Server and Socket classes accept type parameters that describe your events, and the client accepts the same ones. This lesson shows the pattern, then builds a small typed event emitter you can run, to see how the types work without the library.

The socket.io packages are not installed in the runner on this site. The real server and client code is shown read-only. The runnable TypeScript examples use a stand-in emitter typed in the same way, and they are checked by the real type checker.

Four interfaces

The Server class takes four generics: events the client sends, events the server sends, events between servers, and the shape of socket.data.

TypeScript
// shared/events.ts (imported by both server and client)
export interface ServerToClientEvents {
  noArg: () => void;
  message: (from: string, text: string) => void;
  userCount: (count: number) => void;
}

export interface ClientToServerEvents {
  hello: () => void;
  say: (text: string, ack: (result: { ok: boolean; id?: number }) => void) => void;
  join: (room: string) => void;
}

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

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

Notice the direction of the names. ClientToServerEvents lists what the server listens to; ServerToClientEvents lists what the server emits. The ack of an event is just the last parameter of the handler type, and it is typed like any callback.

Server

TypeScript
import { Server } from "socket.io";
import type {
  ClientToServerEvents,
  ServerToClientEvents,
  InterServerEvents,
  SocketData,
} from "./shared/events.js";

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

io.on("connection", (socket) => {
  socket.on("say", (text, ack) => {
    // text: string, ack: (result: {ok: boolean; id?: number}) => void
    socket.broadcast.emit("message", socket.data.name, text);
    ack({ ok: true, id: Date.now() });
  });

  socket.emit("userCount", 1);
  // socket.emit("userCount", "1");   // error: string is not assignable to number
  // socket.emit("mesage", "x", "y"); // error: unknown event
});

Client

The client reverses the two event maps, because its emits are the server's listens:

TypeScript
import { io, Socket } from "socket.io-client";
import type { ClientToServerEvents, ServerToClientEvents } from "./shared/events.js";

const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io("http://localhost:3000");

socket.on("message", (from, text) => console.log(`${from}: ${text}`));
socket.emit("say", "hi", (result) => console.log(result.ok));

If you swap the generics by mistake, the compiler complains at the first call, which is a good way to notice it.

How it works: an event map

The trick behind these types is an event map: an object type whose keys are event names and whose values are function types. A generic class uses keyof and indexed access to make every method depend on the map.

TypeScript A typed emitter in 30 lines (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Args<Listen, E> (a conditional type with infer) extracts the argument list of the handler type for the event E. Because E is inferred from the string you pass, the compiler knows the types of every later argument. In the on("say", (text, ack) => ...) call you do not annotate text or ack; they are inferred.

Typing socket.data

socket.data is a place to store per-connection information, such as the user name set by middleware. With the fourth generic it is typed:

TypeScript
io.use(async (socket, next) => {
  const user = await verifyToken(socket.handshake.auth.token);
  socket.data.name = user.name;   // typed: string
  socket.data.age = user.age;     // typed: number
  next();
});

Remember that TypeScript trusts you: socket.data starts empty at runtime, and the type does not make the fields exist. Set the fields before reading them, or declare them optional.

Rooms and namespaces keep the types

io.to("room").emit(...) and socket.broadcast.emit(...) use the same ServerToClientEvents, so broadcast calls are checked too. Namespaces can have their own maps:

TypeScript
const admin = io.of("/admin") as Namespace<AdminClientEvents, AdminServerEvents, InterServerEvents, SocketData>;

Keep one shared events.ts per namespace and import it on both ends, ideally from a package in a monorepo, so a change is a compile error everywhere at once.

Types are not validation

Types vanish at runtime. A client built in another language, or a modified browser, can send anything. For payloads that matter, validate in the handler:

TypeScript Compile-time types plus runtime validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The handler declares its argument as unknown and narrows it, which is the honest type for data from the network. Real servers also reject unexpected extra fields and cap sizes (see security hardening).

Tips

  • Name event maps after direction (ClientToServerEvents) so nobody confuses them.
  • Put acks last in the signature; they stay inferred.
  • Use socket.timeout(ms).emit(...) with typed acks: the callback then gets (err, response), and the types follow.
  • Strict mode ("strict": true) is what makes these errors appear. Without it, many mistakes pass.
  • When an event has no payload, write it as () => void; do not omit it from the map, or it will be rejected.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. On the server, which interface lists the events the server listens to?

    ClientToServerEvents describes what clients emit, which is what the server handles with socket.on.
  2. 2. What changes on the client when you declare Socket<ServerToClientEvents, ClientToServerEvents>?

    The client listens to server events and emits client events, so the two maps are passed in the opposite order of the server's Server generics.
  3. 3. Why do you still need runtime validation with TypeScript types?

    Types are erased when compiled, so payloads from the network must be checked in the handler.

Summary

  • Server takes four generics: client-to-server, server-to-client, inter-server events, and socket.data.
  • The client reverses the two main maps.
  • An event map plus keyof and an infer-based helper type makes names and argument lists type-checked.
  • Types do not validate input; treat payloads as unknown and check them.
  • Share one events file between server and client.

Next: Browser Clients and Frameworks