withCleanup

function withCleanup<TClient>(client, cleanup): Disposable & TClient;

Wraps a client with a cleanup function, making it Disposable.

Plugin authors can use this to register teardown logic (e.g. closing connections or clearing timers) that runs when the client is disposed. If the client already implements Symbol.dispose, the existing dispose logic is chained so that it runs after the new cleanup function.

Type Parameters

Type ParameterDescription
TClient extends objectThe type of the original client.

Parameters

ParameterTypeDescription
clientTClientThe client to wrap.
cleanup() => voidThe cleanup function to run when the client is disposed.

Returns

Disposable & TClient

A new client that extends TClient and implements Disposable.

Example

Register a cleanup function in a plugin that opens a WebSocket connection.

function myPlugin() {
    return <T extends object>(client: T) => {
        const socket = new WebSocket('wss://api.example.com');
        return withCleanup(
            extendClient(client, { socket }),
            () => socket.close(),
        );
    };
}
 
// Later, when the client is no longer needed:
using client = createClient().use(myPlugin();
// `socket.close()` is called automatically when `client` goes out of scope.

See

extendClient

On this page