Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving more data on socket.io object in typescript

I usually used to do something like socket.username = username when not using typescript. But now i am and when i try to save it the same way it gives me the error

Property 'username' does not exist on type 'Socket'

I know this means i need to extend it, but i have tried it like so

interface Socket {
        username: any
}

But it did not help and i also tried this,

interface SocketIO {
        username: any
}

With no luck.

like image 656
mega-crazy Avatar asked May 09 '26 08:05

mega-crazy


2 Answers

Just socket['username'] = username should do the trick.

If you want type safety and if you want to have autocompletion for the username property, you can extend the Socket interface.

interface ExtendedSocket extends Socket {
  username: string;
}

Then you can cast the original Socket to your custom type:

const mySocket = <ExtendedSocket>socket;
mySocket.username = 'user1'; // won't throw errors and autocomplete will work
like image 100
Tsvetan Ganev Avatar answered May 12 '26 07:05

Tsvetan Ganev


If you want to add extra information to the socket object, you can add this information to socket.data object which is declared with any in their declaration file

Below is a snippet from socket.d.ts file

/**
* Additional information that can be attached to the Socket instance and which will be used in the fetchSockets method
*/
data: any;
like image 34
harsh Avatar answered May 12 '26 07:05

harsh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!