Typescript events per namespace #4481
-
How can i provide the events per namespace, because i have events that have the same name but different values depending on the namespace |
Beta Was this translation helpful? Give feedback.
Answered by
darrachequesne
Oct 11, 2022
Replies: 1 comment 1 reply
-
Hi! You can provide the event types when creating the namespace: import { Server, Namespace } from "socket.io";
// types for the main namespace
const io = new Server<ClientToServerEvents, ServerToClientEvents, InterServerEvents, SocketData>();
// types for the namespace named "/my-namespace"
interface NamespaceSpecificClientToServerEvents {
foo: (arg: string) => void
}
interface NamespaceSpecificServerToClientEvents {
bar: (arg: string) => void;
}
interface NamespaceSpecificInterServerEvents {
// ...
}
interface NamespaceSpecificSocketData {
// ...
}
const myNamespace: Namespace<
NamespaceSpecificClientToServerEvents,
NamespaceSpecificServerToClientEvents,
NamespaceSpecificInterServerEvents,
NamespaceSpecificSocketData
> = io.of("/my-namespace");
myNamespace.on("connection", (socket) => {
socket.on("foo", () => {
// ...
});
socket.emit("bar", "123");
}); And on the client side: import { io, Socket } from "socket.io-client";
const socket: Socket<
NamespaceSpecificServerToClientEvents,
NamespaceSpecificClientToServerEvents
> = io("/my-namespace");
socket.on("bar", (arg) => {
console.log(arg); // "123"
}); Added in the documentation here: https://socket.io/docs/v4/typescript/#custom-types-for-each-namespace |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
darrachequesne
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi! You can provide the event types when creating the namespace: