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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With