From 9d622991857b9626529e049d0724288da9f25d15 Mon Sep 17 00:00:00 2001 From: Damien Arrachequesne Date: Sat, 15 Oct 2022 08:22:38 +0200 Subject: [PATCH] docs: add example of `socket.timeout().emit()` with types Related: https://github.com/socketio/socket.io-client/issues/1555 --- .../categories/01-Documentation/typescript.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/docs/categories/01-Documentation/typescript.md b/docs/categories/01-Documentation/typescript.md index fba68642..5114284b 100644 --- a/docs/categories/01-Documentation/typescript.md +++ b/docs/categories/01-Documentation/typescript.md @@ -188,3 +188,36 @@ socket.on("bar", (arg) => { console.log(arg); // "123" }); ``` + +## Emitting with a timeout + +Emitting with a timeout breaks the symmetry between the sender and the receiver, because the sender has an additional error argument in case of failure. + +This can be fixed with a little helper type: + +```ts +type WithTimeoutAck = isSender extends true ? [Error, ...args] : args; + +interface ClientToServerEvents { + hello: (arg: number, callback: (...args: WithTimeoutAck) => void) => void; +} + +interface ServerToClientEvents { + // ... +} + +const io = new Server>(3000); + +io.on("connection", (socket) => { + socket.on("hello", (arg, cb) => { + // arg is properly inferred as a number + cb("456"); + }); +}); + +const socket: Socket> = ioc("http://localhost:3000"); + +socket.timeout(100).emit("hello", 123, (err, arg) => { + // arg is properly inferred as a string +}); +```