In my Typescript code, I have created a basic User
class as shown below:
export class User {
constructor(public id: string);
}
When I emit a message from my socket.io server, I include an instance of the User
class like this:
var user = new User('billy');
io.emit('MyMessage', user);
On the client side, I am listening for the same message like so:
io.on('MyMessage', (user: User) => {
console.log(user); // This outputs '[object]'
console.log(user.id); // This outputs 'undefined'
console.log(user[0].id); // This outputs 'billy'
}
It seems that the data sent between sockets is treated as an array of objects. The TypeScript definition of the emit
method also supports this, as seen below:
emit( event: string, ...args: any[]): Namespace;
Therefore, is using array addressing like user[0].id
the best way to access the sent data, or is there a cleaner method available?