Socket.io additional attributes on typescript do not exist

Viewed 3155

I am using Socket.io v4.0.1 with typescript and a node/express server which works as intended. The problem is that on connection I want to emit to the client socket its sessionID and userID, which are addition attributes on my server socket instance, but typescript is throwing the following type errors.

io.on("connection", (socket: Socket): void => {
  console.log(socket.id);

  socket.emit("session", {
    sessionID: socket.sessionID, // property sessionID does not exist on type Socket<DefaultEventsMap,DefaultEventsMap>
    userID: socket.userID,// property userID does not exist on type Socket<DefaultEventsMap,DefaultEventsMap>
  });
});

Is there any way to add this additional attributes to the type definition without changing the type definitions itself (@types/socket.io) ?

socketio's additional attributes documentation

2 Answers

The solution was to create my own interface, which extends form the Socket type and add the desired additional attributes.

interface ISocket extends Socket {
  name?: string;
  // other additional attributes here, example:
  // surname?: string;
}

Although I had already tried that, it threw me another error, which basically said that the types Socket and ISocket could not be compatible, because the property "name" was missing on type Socket and required in type ISocket.

The solution to that problem was to add the "?" in name?: string. This makes the field not required in the interface.

Thanks to @halilcakar for helping me out.

Try to extend Socket interface:

declare module 'socket.io' {
  interface Socket {
    sessionID?: string;
    userID?: string;
    // other additional attributes here, example:
    // surname?: string;
  }
}

...

io.on("connection", (socket: Socket): void => {
  console.log(socket.id);

  socket.emit("session", {
    sessionID: socket.sessionID,  // OK
    userID: socket.userID,        // OK
  });
});
Related