withCleanup

function withCleanup<TClient>(
    client,
    cleanup,
): {
    [K in string | number | symbol]: (Omit<TClient, typeof dispose> &
        Disposable)[K];
};

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.

The return type is an ExtendedClient, which flattens the merged shape into a single object literal so chained calls do not accumulate nested intersections in editor tooltips and error messages.

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

{ [K in string | number | symbol]: (Omit<TClient, typeof dispose> & Disposable)[K] }

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

On this page