Sub topic 7
Optional Resources: null, undefined, and TypeErrors
This chapter assumes you already know how using and await using bind a resource and dispose it when the block exits, and that you can write an object with Symbol.dispose or Symbol.asyncDispose. It also assumes you are comfortable with try/catch, the falsy values in JavaScript, and the microtask queue. The examples need a runtime that supports explicit resource management natively, such as Node.js 24 or later or a recent Chromium-based browser.
Real code often holds a resource only some of the time. A debug log file might be opened only in verbose mode. A cache connection might be missing in tests. The using declaration supports this directly: you can bind null or undefined, and nothing happens at disposal time. Any other value without a usable dispose method gets a TypeError, and it is thrown at the declaration, not when the block exits.
The Validation Rule
When a using declaration runs, the engine checks the value right away and decides whether to register it for disposal:
- If the value is
nullorundefined, it is accepted and nothing is registered. - If the value is not an object (a number, string, boolean, symbol, or bigint), a
TypeErroris thrown. - The engine reads
value[Symbol.dispose]. If that property isundefinedornull, aTypeErroris thrown. If it exists but is not callable, aTypeErroris thrown. - Otherwise the value and the method it just read are pushed onto the scope's disposal list.
await using follows the same steps, with one change in step 3. It looks for Symbol.asyncDispose first and falls back to Symbol.dispose. A TypeError is thrown only when neither exists.
The table below lists what common values do.
| Value bound by `using` | Result |
|---|---|
| `null` | Accepted, nothing disposed |
| `undefined` | Accepted, nothing disposed |
| Object with callable `[Symbol.dispose]` | Registered, disposed at scope exit |
| Function with callable `[Symbol.dispose]` | Registered (functions are objects) |
| Plain object `{}` | `TypeError` at declaration |
| `false`, `0`, `""`, `NaN` | `TypeError` at declaration |
| Object whose `[Symbol.dispose]` is `"close"` | `TypeError` at declaration |
| A `Promise` of a disposable | `TypeError` at declaration (with sync `using`) |
Conditional Resources with null
The null rule is what makes optional resources easy. You write one declaration, and the disposal logic needs no branch:
function openLog(path) {
console.log(`open ${path}`);
return {
write(msg) { console.log(`[${path}] ${msg}`); },
[Symbol.dispose]() { console.log(`close ${path}`); },
};
}
function run(verbose) {
using log = verbose ? openLog("debug.log") : null;
log?.write("starting");
console.log("doing work");
log?.write("finished");
}
run(true);
// open debug.log
// [debug.log] starting
// doing work
// [debug.log] finished
// close debug.log
run(false);
// doing workOptional chaining (log?.write) is the natural partner here. Optional chaining also works on the right-hand side: using conn = pool?.acquire(); produces undefined when pool is missing, and that value is accepted.
Without this rule, you would need a try/finally with if (log) log[Symbol.dispose](), which is the kind of manual cleanup that using exists to remove.
Common Errors
Falsy values that are not null or undefined
The most common bug in optional-resource code is a short-circuit expression:
function makeRes() {
return { [Symbol.dispose]() { console.log("disposed"); } };
}
const enabled = false;
try {
using r = enabled && makeRes(); // value is false, not null
} catch (e) {
console.log(e.name); // "TypeError"
}enabled && makeRes() evaluates to false when the condition fails, and false is a primitive, so the check throws. The same thing happens with count && open() when count is 0, or name && open(name) when name is "". Only null and undefined are exempt. Use a conditional expression that yields null instead:
using r = enabled ? makeRes() : null;Forgetting to await an async factory
Many resource factories are async. Binding the promise itself fails, because a Promise has no Symbol.dispose:
async function openFile(name) {
return { name, [Symbol.dispose]() { console.log(`close ${name}`); } };
}
async function main() {
try {
using f = openFile("a.txt"); // Promise, not a disposable
} catch (e) {
console.log(e.name); // "TypeError"
}
{
using f = await openFile("a.txt"); // correct: bind the resolved value
console.log(`using ${f.name}`);
}
// using a.txt
// close a.txt
}
main();await using f = openFile("a.txt") also fails, because await using awaits the dispose call at scope exit. It does not await the initializer. A promise has neither Symbol.asyncDispose nor Symbol.dispose, so you still get a TypeError. The correct form is await using f = await openFile(...).
Wrong property name or a non-function method
Objects from older libraries often expose close() or release() and no Symbol.dispose. Binding one with using throws immediately. That is useful, because the mistake shows up the first time the line runs, not as a quiet leak. A property set to a non-function, such as { [Symbol.dispose]: "close" }, throws for the same reason. To adapt such objects, give them a real dispose method or register them with DisposableStack.prototype.adopt, which a later chapter covers.
What Happens When the Check Throws
The TypeError is thrown in the middle of the block, so the block exits abruptly. The normal disposal rules then apply to everything registered before the failing declaration:
function openResource(name) {
console.log(`open ${name}`);
return {
name,
[Symbol.dispose]() { console.log(`close ${name}`); },
};
}
try {
using a = openResource("a");
using b = { name: "b" }; // no Symbol.dispose
console.log("never runs");
} catch (e) {
console.log(`caught ${e.name}`);
}
// open a
// close a
// caught TypeErrorThree details matter here:
ais disposed, because it was registered before the error.- The invalid value
bis never disposed, because it was never registered. If that object held a real handle under a different method name, the handle leaks. TheTypeErrorpoints to the problem, but it does not clean up for you. - If disposing
aalso throws, theTypeErrorbecomes thesuppressedpart of aSuppressedError, just like any other body error.
The Method Is Captured at Declaration Time
The check in step 3 does more than validate. The engine stores the method it found and calls that stored function at scope exit. Changing the property afterward has no effect:
const res = {
[Symbol.dispose]() { console.log("original dispose"); },
};
{
using r = res;
res[Symbol.dispose] = () => console.log("replacement dispose");
}
// original disposeThe reverse is also true. Deleting the property after declaration does not cancel disposal, and adding a dispose method to an object later does not make an earlier failed declaration valid. If a resource needs to switch off its own cleanup, for example after the caller has closed it explicitly, keep that state inside the object and make the dispose method return early. Don't try to patch the method.
await using with null Still Awaits
await using x = null is allowed and disposes nothing. It still guarantees an await at scope exit, so the block's timing stays the same whether or not the resource is present. Code after the block always resumes in a later microtask:
async function run(useAwait) {
Promise.resolve().then(() => console.log(" other microtask"));
if (useAwait) {
await using r = null;
console.log(" body");
} else {
using r = null;
console.log(" body");
}
console.log(" after block");
}
async function main() {
console.log("await using:");
await run(true);
console.log("using:");
await run(false);
}
main();
// await using:
// body
// other microtask
// after block
// using:
// body
// after block
// other microtaskThis is deliberate. If a null resource skipped the await, the same function would sometimes yield to other tasks at the end of a block and sometimes not, depending on runtime data. That kind of inconsistency causes ordering bugs that are hard to reproduce. Because the await always happens, the presence of the resource cannot change scheduling.
Limits of the null Pattern
Binding null works when you know at declaration time whether you have a resource. It does not work when the resource shows up later in the block, because a using binding is constant like const:
function makeRes() {
return { [Symbol.dispose]() {} };
}
function lateBinding() {
using r = null;
// r = makeRes(); // SyntaxError if uncommented, like assigning to const
}Even if reassignment were allowed, the disposal list was already fixed when the declaration ran. For resources acquired later, a varying number of resources, or resources acquired in a loop with early exits, use DisposableStack. That is the subject of a later chapter.
A quick guide:
| Situation | Approach |
|---|---|
| Resource present or absent, known up front | `using x = cond ? open() : null` |
| Resource may come from an optional source | `using x = source?.open()` |
| Resource acquired partway through the block | `DisposableStack` with `stack.use(...)` |
| Object has `close()` but no `Symbol.dispose` | Wrap it, or `stack.adopt(obj, o => o.close())` |
Exercise
A function contains using cache = config.cacheSize && openCache(config.cacheSize);. It works in production but throws a TypeError in tests, where config.cacheSize is 0. Explain the error and rewrite the line so it works in both environments.
Show answer
When config.cacheSize is 0, the && expression evaluates to 0. That is a primitive, not null or undefined, so the using check throws a TypeError at the declaration. Rewrite it with a ternary whose "absent" branch is null: using cache = config.cacheSize ? openCache(config.cacheSize) : null;. Using ?? null would not help, because 0 ?? null is still 0.
Exercise
In { using a = openA(); using b = legacyHandle(); using c = openC(); }, legacyHandle() returns an object with a close() method and no Symbol.dispose. Which functions run, which resources are disposed, and what risk remains?
Show answer
openA() runs and a is registered. legacyHandle() runs, and the declaration of b throws a TypeError because no dispose method is found. openC() never runs. The block exits abruptly, so a is disposed and the TypeError propagates. The legacy handle was never registered, so its close() is never called and that handle leaks. The fix is to adapt it, for example with a wrapper that defines [Symbol.dispose]() { handle.close(); }, or with DisposableStack.prototype.adopt.
Exercise
Why does await using r = null; still cause an await when the block exits, while using r = null; does not?
Show answer
await using guarantees at least one await at scope exit whenever an await using declaration was evaluated, even if every value was null or undefined. That way code after the block always resumes in a later microtask, whether or not a resource was present, and the async timing does not depend on runtime data. Sync using never awaits, so a null binding there has no effect at all.