Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 96 ยท Modern Features

using Declarations and Explicit Resource Management

Clean up resources automatically in TypeScript with using and await using, Symbol.dispose, Symbol.asyncDispose, DisposableStack and SuppressedError.

Programs constantly borrow things that must be given back: file handles, database connections, locks, timers, temporary directories, event subscriptions. Forget to release one and you get leaks, locked files or a pool that runs dry. The traditional fix is try/finally, which works but gets clumsy fast: every resource needs its own block, the cleanup sits far from the setup, and nested resources turn into a staircase of indentation.

Explicit resource management is a JavaScript feature, supported in TypeScript since 5.2, that solves this with one keyword. Declare a variable with using instead of const, and when the enclosing block ends, however it ends (normally, by return, by break or by an exception), the runtime calls the value's [Symbol.dispose]() method. await using does the same for cleanup that is asynchronous. This lesson covers both, the Disposable types behind them, the DisposableStack helpers, and what happens when cleanup itself fails.

The problem with try/finally

Here's the old way, with a small simulated resource. It works, but notice how the cleanup code has to be repeated in the right order for every resource:

TypeScript
const connection = openConnection();
try {
  const lock = connection.lock('orders');
  try {
    lock.write('...');
  } finally {
    lock.release();
  }
} finally {
  connection.close();
}

With using, the same code says what it means: "these values live until the end of this block":

TypeScript
using connection = openConnection();
using lock = connection.lock('orders');
lock.write('...');
// lock is released, then connection is closed, automatically

Your first using declaration

A value you can using must be disposable: it has a method keyed by the well-known symbol Symbol.dispose. TypeScript describes this with the built-in Disposable interface, so a class just implements Disposable and provides the method:

TypeScript using disposes at the end of the block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Both calls print open primary, open replica, then close replica, close primary. Three rules are visible here:

  • Disposal happens at block exit, after the return value is computed but before the caller receives it. That's why the report line is printed after both close lines.
  • Resources are disposed in reverse order, like a stack: the last one acquired is released first. The replica might depend on the primary, so it goes first.
  • Exceptions don't skip disposal. In the failing call, both connections close before the catch runs.

A using variable is also implicitly const: you can't reassign it, so the runtime always disposes exactly the value you acquired.

What TypeScript checks

The compiler verifies that every using initializer is disposable. Values that merely have a close() or release() method don't count. This example fails on purpose, with the two mistakes people make most often:

TypeScript Values using does not accept (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(7,20): error TS2741: Property '[Symbol.dispose]' is missing in type '{ close(): void; }' but required in type 'Disposable'.
main.ts(9,7): error TS1492: 'using' declarations may not have binding patterns.

The first error says exactly what's missing. The fix for an object you don't control is to wrap it: using connection = { [Symbol.dispose]: () => socket.close() };, or the DisposableStack.adopt() helper shown later. The second error is a rule of the feature: destructuring is not allowed, because the runtime needs to dispose one specific value. Write using pair = ...; and read pair.handle instead.

Two values are allowed besides disposables: null and undefined. using maybe = condition ? acquire() : null; simply skips disposal when there's nothing to dispose.

When cleanup throws: SuppressedError

What if a dispose method throws while an exception is already in flight? JavaScript doesn't silently drop either error. It wraps them in a SuppressedError whose error property is the newer error (from disposal) and whose suppressed property is the one it replaced:

TypeScript Errors during disposal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In case 2, lock fails to dispose, but file is still disposed afterward; one failing cleanup never prevents the others. The caught value is a SuppressedError with the message An error was suppressed during disposal., error set to could not release lock, and suppressed set to write failed. Both error and suppressed are typed any in the library, so narrow them like any caught error.

await using: asynchronous cleanup

Many resources need asynchronous cleanup: flushing a buffer to disk, closing a network connection gracefully, committing a transaction. For those, implement [Symbol.asyncDispose](), which returns a promise, and declare the variable with await using. At block exit the runtime awaits the disposal before moving on. That can only happen where await is allowed: inside an async function, or at the top level of a module like our editor's main.ts.

Node's own file handles from node:fs/promises already implement Symbol.asyncDispose, so this example combines a custom async resource with a real file:

TypeScript await using with a custom resource and a FileHandle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows the pattern that makes this so useful for transactions: BEGIN #1, COMMIT #1, then BEGIN #2, ROLLBACK #2 and failed: amount must be positive. Every exit path that skips commit() rolls back, and you can't forget to write the rollback because there's nowhere else to write it.

await using also accepts plain synchronous Disposable values, so you can mix both kinds in one block. TypeScript's AsyncDisposable interface requires [Symbol.asyncDispose](): PromiseLike<void>.

Node 24 makes several built-ins disposable: FileHandle (async), timers returned by setTimeout/setInterval (disposing clears them), and more in each release. Look for [Symbol.dispose] or [Symbol.asyncDispose] in an API's type definition; your editor's autocomplete shows it.

DisposableStack: managing many resources

using is tied to a block. Sometimes you need more flexibility: a variable number of resources, cleanup for a value that isn't disposable, or a constructor that acquires several resources and must release the ones it already got if a later one fails. DisposableStack (and its twin AsyncDisposableStack) is a disposable container for exactly those cases:

Method What it does
stack.use(value) Adds a disposable (or null/undefined) and returns it
stack.adopt(value, onDispose) Adds a non-disposable value with a cleanup callback, returns the value
stack.defer(callback) Adds a cleanup callback with no value
stack.move() Transfers everything to a new stack and leaves this one empty
stack.dispose() Disposes everything in reverse order (also [Symbol.dispose])
stack.disposed true once disposed

The move() method enables an important pattern: acquire resources inside a using stack so that a failure halfway cleans up automatically, and on success move them out to an object that owns them from then on:

TypeScript DisposableStack with use, adopt, defer and move

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In the success case, nothing is cleaned up when the constructor ends, because move() emptied the local stack before its using scope closed. The resources are released in reverse order only when the pipeline block ends: close output, flush logs, release legacy handle 7, close input.

In the failure case, opening output throws. The constructor's using stack is disposed on the way out, so flush logs, release legacy handle 7 and close input still run, and only then does the cannot open output error reach the caller. Without the stack, a constructor that fails halfway leaks everything it had already opened.

AsyncDisposableStack has the same methods with async versions (disposeAsync(), [Symbol.asyncDispose]), and its use, adopt and defer accept async cleanup.

Support and configuration

using and await using come from the TC39 Explicit Resource Management proposal. V8 ships it natively (Chrome 134+, Node 24+), and so does Firefox; check other engines before relying on native support. TypeScript compiles the syntax down for older targets, but the runtime pieces, Symbol.dispose, Symbol.asyncDispose, DisposableStack, AsyncDisposableStack and SuppressedError, must exist. On older runtimes, load a polyfill (core-js has one).

For the types, include the declarations in your lib:

JSON
{
  "compilerOptions": {
    "target": "es2024",
    "lib": ["es2024", "esnext.disposable"]
  }
}

Our editor uses "lib": ["esnext"], which includes them. See the tsconfig lesson for how target and lib interact.

Good habits with using

  • Implement Disposable on classes that own resources. Anything with a close(), release() or unsubscribe() method is a candidate. Keep the old method too, and have [Symbol.dispose] call it.
  • Make dispose idempotent. Disposing twice (explicitly, then by a stack) should be harmless. Track a #disposed flag.
  • Keep scopes small. A resource lives until the end of its block; use an inner { ... } block to release it early, as in the FileHandle example.
  • Don't return a using variable. It's disposed when the function exits, so the caller would receive a closed resource. Return a fresh object, or use the DisposableStack.move() pattern.
  • Prefer await using for async cleanup. A sync [Symbol.dispose] that starts async work can't be awaited, and failures in it go unnoticed.
  • Generators already clean up. Breaking out of a for...of loop calls the generator's return(), which runs its finally blocks and disposes any using declarations inside it (see Iterators and Generators).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A block declares using a = ...; and then using b = ...;. In which order are they disposed when the block ends?

    Disposal works like a stack, last in first out. Later resources may depend on earlier ones, so they are released first.
  2. 2. Does using conn = { close() {} }; compile?

    using requires a Disposable, an object with a Symbol.dispose method (or null or undefined). A close method is not enough; wrap it or use DisposableStack.adopt.
  3. 3. The body of a using block throws Error A, and then a dispose method throws Error B. What is caught?

    The newer error from disposal becomes error, and the error it replaced becomes suppressed, so no information is lost.
  4. 4. Where can await using be used?

    The runtime awaits the disposal at block exit, so await using needs a context where await is allowed.
  5. 5. Why does the Pipeline constructor call stack.move() at the end?

    If the constructor fails, the using stack disposes everything acquired so far. On success, move() hands the resources to a new stack owned by the object, so they stay open until the Pipeline is disposed.

Summary

  • using x = value; disposes value by calling [Symbol.dispose]() when the block exits, whether normally, by return/break, or by an exception. Several using declarations are disposed in reverse order.
  • TypeScript requires the value to be Disposable (or null/undefined); close() alone gives TS2741. using variables are const and can't destructure (TS1492).
  • If disposal throws while another error is in flight, you catch a SuppressedError with error (from disposal) and suppressed (the original). Other resources are still disposed.
  • await using awaits [Symbol.asyncDispose]() at block exit; it needs an async context. Node's FileHandle and timers are already disposable.
  • DisposableStack and AsyncDisposableStack collect resources with use, adopt and defer; move() transfers ownership out of a scope, which makes constructors that acquire several resources leak-free.
  • Native support exists in V8 (Node 24+, Chrome 134+) and Firefox. TypeScript downlevels the syntax; older runtimes need a polyfill for DisposableStack and friends, and your lib must include esnext.disposable (or esnext).

Next: The satisfies Operator