-
Couldn't load subscription status.
- Fork 10.1k
Description
Is your feature request related to a problem? Please describe.
When you define a listener function for the socket disconnect event in-line, TypeScript correctly infers the type of the reason argument to be DisconnectReason:
socket.on('disconnect', (reason) => {
// Type of 'reason' is 'DisconnectReason'
console.log(`reason: ${reason}`);
});However, I want to create a listener function for the socket.on('disconnect') event ahead of time (so that I can later call removeListener to remove it). But when I do that, the compiler cannot infer that the type of reason is DisconnectReason:
const listener = (reason) => {
// Type of 'reason' is 'any'
console.log(`reason: ${reason}`);
};
socket.on('disconnect', listener);
// Later...
socket.removeListener('disconnect', listener);I can import DisconnectReason from socket.io/dist/socket and create my listener with reason: DisconnectReason, but it would be ideal if DisconnectReason was exposed as part of the public API, so that I could import it from socket.io directly.
Describe the solution you'd like
I would like to be able to import DisconnectReason from socket.io directly, instead of from socket.io/dist/socket, like so:
import { DisconnectReason } from 'socket.io';Describe alternatives you've considered
I considered trying to determine the type of the listener function via some clever TypeScript, like so:
const listener: Parameters<typeof socket.on<'disconnect'>>[1] = (reason) => {
// Type of 'reason' is 'DisconnectReason'
console.log(`reason: ${reason}`);
};That kind of worked, but I was running into eslint/prettier errors about the syntax, and I don't actually think it's more readable/clear than just using DisconnectReason directly:
const listener = (reason: DisconnectReason) => {
// Type of 'reason' is 'DisconnectReason'
console.log(`reason: ${reason}`);
};Thanks!