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) ?
socket: Socketpart of your code using socket.io's type definition but you can create your own and extend socket.io's Socket definition and add userID and sessionID attributes on it or as an alternative you can create a map object based on users socket.io as key, an object that contains sessionID and userID as values and use this value in global scope of your node app :)io.on("connection", (expects Socket type here) => {...code here})function expects a Socket type variable and not a custom type like you are suggesting. although the second option seems possible (and probably what I'm going to use), it seems to be unconvenient.BaseSocketor smt and create anSocketinterface that extendsBaseSocketand also have more properties on it. I think with Typescript this is an option