1

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?

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Being new to js and ts, the destructuring syntactic sugar is the sweetest thing I've learnt today!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.