Skip to content

Commit

Permalink
docs: add example of socket.timeout().emit() with types
Browse files Browse the repository at this point in the history
  • Loading branch information
darrachequesne committed Oct 15, 2022
1 parent 24b8b71 commit 9d62299
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions docs/categories/01-Documentation/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 boolean, args extends any[]> = isSender extends true ? [Error, ...args] : args;

interface ClientToServerEvents<isSender extends boolean = false> {
hello: (arg: number, callback: (...args: WithTimeoutAck<isSender, [string]>) => void) => void;
}

interface ServerToClientEvents<isSender extends boolean = false> {
// ...
}

const io = new Server<ClientToServerEvents, ServerToClientEvents<true>>(3000);

io.on("connection", (socket) => {
socket.on("hello", (arg, cb) => {
// arg is properly inferred as a number
cb("456");
});
});

const socket: Socket<ServerToClientEvents, ClientToServerEvents<true>> = ioc("http://localhost:3000");

socket.timeout(100).emit("hello", 123, (err, arg) => {
// arg is properly inferred as a string
});
```

1 comment on commit 9d62299

@vercel
Copy link

@vercel vercel bot commented on 9d62299 Oct 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please # to comment.