Sub topic 14
Using the Feature Today: Runtimes, TypeScript, and Babel
The earlier chapters treated using, await using, and the disposable stacks as if every engine already ran them. Support is uneven in practice. Some runtimes ship the syntax and globals natively, some ship only parts of it, and some need a compiler and a polyfill. This chapter shows how to find out what your target supports, how to set up TypeScript and Babel to compile the syntax, and what breaks when the setup is only partly right.
The chapter assumes you can read a tsconfig.json or a Babel config and that you know the difference between transpiling syntax and polyfilling globals.
Two Separate Pieces: Syntax and Runtime Globals
Explicit resource management has two parts, and they reach engines at different times:
| Piece | What it includes | How you get it without native support |
|---|---|---|
| Syntax | `using`, `await using`, `for (using x of ...)` | A compiler (TypeScript, Babel, or a bundler) rewrites it into `try`/`catch`/`finally` plus helper calls |
| Globals | `Symbol.dispose`, `Symbol.asyncDispose`, `DisposableStack`, `AsyncDisposableStack`, `SuppressedError` | A polyfill such as core-js, or a small hand-written shim |
The compiled form of using still looks up Symbol.dispose when the program runs. Compiling the syntax is therefore not enough. If the symbol does not exist at runtime, the compiled code either throws or cannot find your dispose method. The reverse case also happens: a runtime can have Symbol.dispose and no using syntax. Node.js 18 and 20 are like this. They added the symbols so that their own APIs could be disposable, but they do not parse using.
Native Runtime Support
Support has changed quickly, so check the current compatibility tables (MDN, caniuse, or your runtime's release notes) before you rely on anything below. As of late 2026 the general picture is:
| Runtime | Native status |
|---|---|
| Chrome / Edge (V8) | Syntax and globals shipped (Chrome 134 and later) |
| Node.js | Full native support from Node 24 (V8 13.x). Node 18.18+/20.x define the symbols only |
| Firefox | Syntax and globals shipped (Firefox 134 and later) |
| Deno | Supported. Deno uses V8 and its TypeScript pipeline |
| Bun | `using` supported through Bun's built-in transpiler |
| Safari | Check current status. Support arrived later than in other engines |
If you only target recent Chromium, Firefox, and Node 24 or newer, you can write the feature as-is and ship it. Most libraries and most browser applications cannot assume that yet.
Feature Detection
The globals are easy to detect. The syntax is harder, because a script that contains using fails to parse on an engine without support, and then none of the script runs. To test the syntax, compile a snippet at runtime:
function detectResourceManagement() {
const globals = {
dispose: typeof Symbol.dispose === "symbol",
asyncDispose: typeof Symbol.asyncDispose === "symbol",
DisposableStack: typeof globalThis.DisposableStack === "function",
AsyncDisposableStack: typeof globalThis.AsyncDisposableStack === "function",
SuppressedError: typeof globalThis.SuppressedError === "function",
};
let syntax = false;
try {
// A function body is a valid place for using; null is an allowed value.
new Function("{ using x = null; }");
syntax = true;
} catch {
syntax = false;
}
return { syntax, ...globals };
}
console.log(detectResourceManagement());On Node 20 the output shows syntax: false and dispose: true. On Node 24 every field is true. new Function is blocked under a strict Content Security Policy that omits 'unsafe-eval', so do this check in tests or build tooling, not in production page code.
TypeScript
TypeScript has supported using and await using since version 5.2. Two settings matter.
target decides whether TypeScript rewrites the syntax. If the target is lower than the level where using is standard (for example ES2022), the compiler turns each block into a try/catch/finally and calls the helpers __addDisposableResource and __disposeResources. These helpers keep the semantics from earlier chapters: reverse order, null/undefined skipped, and SuppressedError chaining. With target: "ESNext" the syntax is emitted unchanged, so the runtime must parse it.
lib decides which types exist. The declarations for Disposable, AsyncDisposable, DisposableStack, AsyncDisposableStack, SuppressedError, and the two symbols live in esnext.disposable, which is also included in esnext.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"lib": ["ES2022", "esnext.disposable", "DOM"],
"strict": true,
"importHelpers": true,
"sourceMap": true
}
}importHelpers: true makes the compiler import the helpers from tslib instead of copying them into every file. Install a tslib version recent enough to include the disposal helpers (2.6 or later).
Type checking also enforces the protocol. using x = value requires value to be Disposable | null | undefined, and await using accepts AsyncDisposable, Disposable, null, or undefined. If an object only has a method named dispose, without the symbol key, you get a compile-time error. Without TypeScript you would only find that out at runtime.
class TempFile implements Disposable {
constructor(public path: string) {}
[Symbol.dispose](): void {
console.log(`removing ${this.path}`);
}
}
function work(): void {
using file = new TempFile("/tmp/report.csv");
console.log(`writing ${file.path}`);
}
work();The TypeScript helper falls back to its own SuppressedError-like object when the global is missing, so error chaining still works on older engines. instanceof SuppressedError fails, though, unless a polyfill defines the global.
Babel
In Babel, the syntax transform comes from @babel/plugin-proposal-explicit-resource-management. Depending on your Babel version and how far the proposal has progressed, @babel/preset-env may already include it. Adding the plugin explicitly works in both cases.
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/plugin-proposal-explicit-resource-management
npm install core-js{
"presets": [
["@babel/preset-env", { "targets": "defaults" }]
],
"plugins": [
"@babel/plugin-proposal-explicit-resource-management"
]
}Save that as babel.config.json and compile with npx babel src --out-dir dist. The plugin rewrites using and await using into helper calls and does not add globals. Load core-js for those, at the very top of your entry point:
// src/index.js
import "core-js/proposals/explicit-resource-management";
function openResource(name) {
return { name, [Symbol.dispose]() { console.log(`close ${name}`); } };
}
{
using stack = new DisposableStack();
stack.use(openResource("a"));
stack.defer(() => console.log("deferred"));
}
// deferred
// close aThat core-js entry point defines Symbol.dispose, Symbol.asyncDispose, DisposableStack, AsyncDisposableStack, and SuppressedError, and it leaves native versions alone where they exist. Test runners such as Jest that compile through Babel pick up the same config, so tests and production code use the same transform.
Other tools (esbuild, SWC, and the bundlers built on them) can also lower using in recent versions. Their configuration differs, but the rule from this chapter still applies: they handle syntax, and you supply the globals.
A Minimal Shim When You Only Need the Symbols
Sometimes core-js is more than you want. If you write using and await using through a compiler but never call DisposableStack, defining the two symbols is enough:
// disposable-shim.js — import before any module that defines disposables
Symbol.dispose ??= Symbol.for("Symbol.dispose");
Symbol.asyncDispose ??= Symbol.for("Symbol.asyncDispose");Symbol.for returns the same registered symbol to every copy of the shim, even when a bundle contains the shim twice. With plain Symbol("..."), two copies would produce two different symbols, and one library's dispose method would be invisible to another library's using helper.
Gotchas and Failure Modes
Polyfill load order
A class body such as [Symbol.dispose]() {} evaluates Symbol.dispose once, when the class is defined. If the polyfill runs after that module, the method is stored under the key "undefined" (a string), and later disposal finds nothing. Import the polyfill first, before any module that defines disposable classes, and make sure your bundler does not reorder it.
Mismatched symbols
Two different polyfills can define Symbol.dispose as two different symbols, for example a library's bundled copy and your application's copy. Each one then fails to recognize the other's disposables, and you get "not disposable" TypeErrors on objects that look correct. Prefer a single polyfill for the whole application, deduplicated in the bundle.
Native syntax with incomplete globals
Shipping target: "ESNext" to an engine that parses using but lacks DisposableStack works until the first new DisposableStack(). Feature-detect the globals separately from the syntax.
Debugging compiled output
Compiled using turns into nested try blocks and helper calls, so stack traces point into helpers like __disposeResources. Turn on source maps (sourceMap in TypeScript, --source-maps in Babel) so that errors map back to the original using line.
Async disposal in sync-only targets
await using compiles to code that relies on async/await. If you target an engine older than ES2017, the compiler also has to lower async functions, which adds size and a regenerator dependency. Most current targets avoid this, but check if you support very old browsers.
Decision Summary
| Situation | Setup |
|---|---|
| Node 24+ or evergreen Chromium/Firefox only | Native. Use `target: "ESNext"` in TypeScript, or no transform |
| Node 18/20, TypeScript project | `target: "ES2022"`, `lib` with `esnext.disposable`, `tslib`, plus core-js if you use stacks |
| Browser app with broad targets | Babel plugin plus core-js entry imported first |
| Library published to npm | Compile `using` down, document that consumers need `Symbol.dispose`, and avoid bundling a private polyfill |
Exercise
A TypeScript project uses target ES2022 and lib ["ES2022", "esnext.disposable"]. It compiles without errors, but on Node 20 the line using stack = new DisposableStack(); throws a ReferenceError. Explain why, and give the smallest fix.
Show answer
The lib setting only adds type declarations, and TypeScript's downlevel transform rewrites the using syntax but does not create globals. Node 20 defines Symbol.dispose but not DisposableStack, so the constructor does not exist at runtime. Fix it by loading a runtime polyfill first, for example import "core-js/proposals/explicit-resource-management"; at the top of the entry point.
Exercise
A module defines class Lock { [Symbol.dispose]() { /* release */ } } and is imported before the module that runs Symbol.dispose ??= Symbol.for("Symbol.dispose"). A later using l = new Lock() throws a TypeError saying the value is not disposable. What happened?
Show answer
The computed key [Symbol.dispose] was evaluated when the class was defined. Symbol.dispose was still undefined then, so the method was stored under the string key "undefined". The shim later created the real symbol, and the compiled using helper looked for a method under that symbol and found none. Import the shim before every module that defines disposables.
Exercise
Why does the feature-detection function test using syntax with new Function(...) instead of writing a using declaration directly inside a try block?
Show answer
A using declaration written directly in the source is a syntax error on engines without support, and a parse error stops the whole script before the try block can run. new Function parses the string at runtime, so an unsupported engine throws a catchable SyntaxError.