James B James B - 4 months ago 42
Javascript Question

Emitting Typescript Data Objects on Socket.IO

I have defined a simple

User
class in Typescript as follows

export class User {
constructor(public id: string);
}


from my socket.io server I emit a message with an instantiated version of this
User
class, e.g.,

var user = new User('billy');
io.emit('MyMessage', user);


on my client I listen for my message as follows

io.on('MyMessage', (user: User) => {
console.log(user); // This prints '[object]'
console.log(user.id); // This prints 'undefined'
console.log(user[0].id); // This prints 'billy'
}


Data between sockets therefore appears to be sent as an array of objects, the typescript definition for the
emit
method also shows this, i.e.,

emit( event: string, ...args: any[]): Namespace;


Thus, is the cleanest way for me to use the sent data to use array addressing as shown in the third console log line above, i.e.,
user[0].id
, or is there a cleaner way to do this?

Answer

seems like you can do

io.emit('MyMessage', user, someData, someAnotherData);

And when you catch it you get

io.on('MyMessage', data => {    
    data[0] // user
    data[1] // someData
    data[2] // someAnotherData
});

You can use destructuring to manage it

io.on('MyMessage', ([user]: [User]) => {    
    console.log(user.id);
});