I'm trying to implement event typeguards, as they're available in Socket.io v4.
This is my attempt of creating an onAndOff function, that listens for a given socket event, and returns a cleanup callback (will later be used in a useEffect):
// somewhere in another file:
export const socket: Socket<ServerToClient, ClientToServer> = io();
function onAndOff<
Event extends keyof ServerToClient = keyof ServerToClient,
Callback = ServerToClient[Event]
>(event: Event, callback: Callback) {
socket.on(event, callback);
return () => socket.off(event, callback);
}
But my IDE marks the callback arguments as an error:
TS2345: Argument of type 'Callback' is not assignable to parameter of type 'FallbackToUntypedListener '.
It seems to be a generic Typescript error, but I'm not sure what wrong with this wrapper function.